KEMBAR78
Unit 10 File | PDF | Computer File | Pointer (Computer Programming)
0% found this document useful (0 votes)
13 views8 pages

Unit 10 File

The document provides an introduction to file management in C programming, explaining the necessity of files for data persistence and organization. It details the types of files (text and binary), common file operations (creating, opening, reading, writing, and closing files), and specific functions used for file management. Additionally, it includes examples of code for reading from and writing to files using various methods.

Uploaded by

shashikant.patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views8 pages

Unit 10 File

The document provides an introduction to file management in C programming, explaining the necessity of files for data persistence and organization. It details the types of files (text and binary), common file operations (creating, opening, reading, writing, and closing files), and specific functions used for file management. Additionally, it includes examples of code for reading from and writing to files using various methods.

Uploaded by

shashikant.patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Introduction to file management

Memory is volatile and its contents would be lost once the program is terminated. So if we need the same data
again it would have to be either entered through the keyboard again or would have to be regenerated
programmatically. Obviously both these operations would be tedious. At such times it becomes necessary to
store the data in a manner that can be later retrieved and displayed either in part or in whole. This medium is
usually a ‘file’ on the disk.

Data Organization
Before we start doing file input/output let us first find out how data is organized on the disk. All data stored
on the disk is in binary form. How this binary data is stored on the disk varies from one OS to another.
However, this does not affect the C programmer since he has to use only the library functions written for the
particular OS to be able to perform input/output. It is the compiler vendor’s responsibility to correctly
implement these library functions by taking the help of OS.

Why files are needed?


1. When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the
program terminates.
2. If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file using a
few commands in C.
3. You can easily move your data from one computer to another without any changes.

Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files

1. Text files

Text files are the normal .txt files. You can easily create text files using any simple text editors such
as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.
2. Binary files

Binary files are mostly the .bin files in your computer.


Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides better security than text
files.

File Operations
In C, you can perform four major operations on files, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Reading from file
4. writing information to a file
5. Closing a file

FILE * fp;
FILE is a keyword in C for representing files and fp is a variable of FILE type.

Simple file management functions for text files

Following are the most important file management functions available in ‘C,’

Function Purpose Syntax


Creating a file or opening an FILE *fopen(“file_name”, “mode”);
fopen ()
existing file
fclose () Closing a file fclose( FILE *fp )
fprintf(FILE *stream, const char *format
fprintf () Writing a block of data to a file
[, argument, ...])
fscanf(FILE *stream, const char *format
fscanf () Reading a block data from a file
[, argument, ...])
fgetc() Used to read characters from a file fgetc(FILE *stream)
fputc() Used to write characters in a file fputc(int c, FILE *stream)
Used to read integral value from fgetw(File *fp)
fgetw()
the file
Used to write integral value in the fputw(int number,File *fp)
fputw ()
file
Sets the position of a file pointer to fseek(FILE *stream, long int offset, int
fseek ()
a specified location whence)
Function Purpose Syntax
Returns the current position of a ftell(FILE *stream)
ftell ()
file pointer
Sets the file pointer at the rewind(FILE *stream)
rewind ()
beginning of a file

Reading from a file


The reading from a file operation is performed using the following pre-defined file
handling methods.

1. getc()
2. getw()
3. fscanf()
4. fgets()
5. fread()

Writing into a file


The writing into a file operation is performed using the following pre-defined file handling
methods.

1. putc()
2. putw()
3. fprintf()
4. fputs()
5. fwrite()

Creating a new file


We use the fopen() function to create a new file as well as open an existing file in our
storage.

The syntax of fopen()- fopen("filename","mode")

When declaring a file in C, the pointer of the file type (FILE) is used to point the
file. fopen() will give the address of the file to the file pointer which is going to create/open.
Let's create a new file with the name file2.txt.

Example:

#include <stdio.h>
int main(){
FILE * file; // pointer of type file.
file = fopen("file2.txt","w");
}
A new file will be created in the folder where your code is saved. You can also specify the
path where you want your file to be created. file = fopen ("C://file2.txt", "w");
We use write mode because it will create a new file if the file is not present.
Opening an Existing File

To open an existing file we use fopen() with the required opening modes as discussed
already. We have already created a file using write mode. In the following code,
use r mode that is open the file in read mode.

Code:

#include <stdio.h>
int main(){
FILE * file;
file = fopen("file2.txt","r");
}

Below are some modes that you can use in fopen() function:-

Mode What it does


r Used to open a text file in read mode
w Used to open a text file in write mode
a Used to open a text file in append mode
r+ Used to open a text file in read and write mode
w+ Used to open a text file in read and write mode
a+ Used to open a text file in read and write mode
rb Used for opening a binary file in read mode
wb Used for opening a binary file in write mode
ab Used for opening a binary file in append mode
Used for opening a binary file in read and
rb+
write mode
Used for opening a binary file in read and
wb+
write mode
Used for opening a binary file in read and
ab+
write mode

Writing Data to a File


Let's write in the file that we created in the previous example. So to do that i'll be
using fprintf() to write a text in the file with the name file2.txt.

Code:

#include <stdio.h>
int main(){
FILE *file;
file = fopen("file2.txt", "w");
fprintf(file, "Hello! Welcome to Scaler academy.\n");
}

Reading Data From an Existing File


To read data from an existing file we will use “r” mode in file opening. To read the file
character by character we use getc() and to read line by line we use fgets().
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fp;
char s;
fp=fopen("file2.txt","r");
if(fp==NULL)
{
printf("\nCAN NOT OPEN FILE");
exit(1);
}
do
{
s=getc(fp); // read file character by character
printf("%c",s);
}
while(s!=EOF);
fclose(fp);

return 0;

Closing the File


To close a file which is already open, we will use fclose(). As we have already discussed
the syntax of it we will directly head over to the example.

#include <stdio.h>
int main(){
FILE *file;
file = fopen("file2.txt", "w");
fprintf(file, "Hello! Welcome to Scaler academy.\n");
fclose(file);
}

Reading from and writing to files.

We utilise the fscanf() and fprintf() to write and read the data to the text file. These are
basically the file versions of the scanf() and printf(). But there is a major difference, i.e.,
both fscanf() and fprintf() expect a pointer pointing towards the structure FILE in the
program.
Example:-1
program to read name and marks of n number of students from and store them in a
file.

Write (fprintf)

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *ptr;
char name[20];
int m;
ptr=fopen("xyz.txt","w");
printf("Enter name & marks");
while((scanf("%s %d",name,&m))!=EOF)
fprintf(ptr,"\n%s %d",name,m);
fclose(ptr);

getch();
}

Read (fscanf)

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *ptr;
char name[20];
int m;

ptr=fopen("xyz.txt","rt");
while((fscanf(ptr,"%s %d",name,&m))!=EOF)
printf("\n%s %d",name,m);
fclose(ptr);
getch();
}

Example:-2

Write (fputc)

#include <stdio.h>
void main() {
FILE *f;
int c,cnt=0;
f = fopen("new.txt", "w");
printf("Enter string");
while((c=getchar())!=EOF)
fputc(c,f);
fclose(f);
}

Read (fgetc)

#include<stdio.h>
#include<conio.h>
void main() {
FILE *f;
char s;

f=fopen("new.txt","r");
while((s=fgetc(f))!=EOF) {
printf("%c",s);
}
fclose(f);
getch();
}

fputs() function
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();

fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);

fclose(fp);
getch();
}

fgets() function
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char text[300];
clrscr();

fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));

fclose(fp);
getch();
}

You might also like