ENOTES

File handling in C with program example

access_time Jul 23, 2021 remove_red_eye 4508

In C programming program runs on main memory, which means data is stored temporarily. We cannot retrieve or access and data for future references. So that we can use it when ever required. To overcome this limitation, C programming has feature of File handling through which we can conveniently handle data for current and future use. Thus, using file handling in C allows programmer to store data in auxiliary (secondary) storage permanently. The data supplied by the user are store in the form of data file in our permanent memory.

File Operation Modes in C

Depending upon the requirement, we can open our data file in various mode. Following are the different modes of opening data file in C programming

File Opening modePurpose
wUsed for opening the file for writing. 
rUsed to open file for reading / displaying provided the file must exist to read or display.
aUsed for opening the file to add at the end .
w+Used for opening the file for both writing and reading,
r+Used for opening the file for both reading and writing. The file must already exist.
a+Used for opening the file for both reading and adding at the end of the file

Basics of data file in C

In order to work with data file in C, we need to know the basic of working with data files. For instance, if we take an input from the user we need to store in files which should be created first. Similarly there are other basics that we should know before storing, writing, reading, displaying and adding data in data file. The syntax and program examples for opening a data file, closing a data file, writing on data file, reading from a data file and adding data in existing data file are explained below.

Opening a data file in C

Before working with data file, we should open our data file in the require ‘file opening mode’. Below is the syntax and example of opening a data file in C.

Syntax for opening data file

FILE *filepointer_variable;
filepointer_variable = fopen(“//path/filename.ext” , “mode”);

This syntax can be used in our program as:
If we want to store data in data file named “record.txt” then

FILE *fptr;
fptr = fopen(“record.txt” , “w”);

If we want to display records from data file named “record.txt” then

FILE *fptr;
fptr = fopen(“record.txt” , “r”);

[Note: mode can be w, r, a, w+, r+ and a+ depending upon the requirements]

Closing a data file in C

Every opened data file during processing must be closed at the end. This can be done by using following syntax.

fclose(filepointer_variable or filename);
Eg; 
fclose(fptr); 
fclose(“record.txt”);

Writing data on a data file in C

After we open data in writing mode, if we need to store data in a data file then, this can be done by using ‘fprintf’ keyword and more. For writing data file must be opened in writing mode i.e. ‘w’. While opening data file in ‘w’ mode, If the file already exists its contents will be erased and new are stored. If the file doesn't exist then it will be created.

Syntax to write data on data file

fprintf (filepointer_variable, “list of format specifier”, list of variables);

This can be used in our program as:
If we want to store data in book id, book name and its price in data file named “library.txt” then

fprintf (fptr, “%d %s %f”, id, name, price);

[Note: As ‘printf’ does not has ‘&’ in its variable list, ‘fprintf’ also doesn’t use ‘&’ ]

Program example

#include 
int main()
{
   char name[10];
   float price;
   int id;
   FILE *fptr;
   fptr = fopen(“library.txt” , ”w”);
   printf("Enter book id name and price”);
   scanf(“%d %s %f”, &id, name ,&price); // stores id name and price in main memory
   fprintf(fptr,“%d %s %f”,id, name ,price); // stores id name and price in secondary memory
   fclose(fptr);
   return 0;
}

The above program stores only one set of records. We need to change the program structure if we want to stores multiples data in data file. Let us say 100 records, N records, Until user press ‘Y’ and as per user requirements. Click here.

Reading data from a data file in C

After we open data in writing mode, if we need to read and display data from a data file then, this can be done by using ‘fscanf’ keyword and more.

Syntax to write data on data file

fscanf (filepointer_variable, “list of format specifier”, list of variables);

This can be used in our program as:
If we want to read and display book id, book name and its price from a data file named “library.txt” then

fscanf (fptr, “%d %s %f”, &id, name, &price);

[Note: As in ‘scanf’ we use ‘&’ in ‘int’ and ‘float’ but not in ‘char’ similarly in ‘fscanf’ also we do same.]

Why EOF (End of File) in C ?

Suppose, you want to display all the books whose price is greater then 500. While displaying, we do not know the exact number of records in the data file to be accessed. So, to overcome that we use EOF (End of file). It is used in program while reading the content back from the file. After the detection of EOF character by the C compiler the reading of the file stops. So, it is used to represent the end state of the file while reading back the content.

Program example 

#include 
int main()
{
   char name[10];
   float price;
   int id;
   FILE *fptr;
   fptr = fopen(“library.txt” , ”r”);
   printf(“Book id \t Book name \t Book Price”); // This will be a heading for our displayed record
   while ( fscanf (fptr, “%d %s %f”, “&id, name, &price”) != EOF ) 
  {
 printf(“%d %s %f”, id, name ,price);
}
   fclose(fptr);
   return 0;
}

The above program displays all the records from the data file ‘record.txt’. if We need to change the program structure if we want display specific records based on conditions then, Let us whose salary is greater than 500, who lives in ‘London’ etc. Click here.

Adding data on a data file in C (Append)

Append means adding data in existing data file, it is similar to writing or storing data in data file. Same ‘fprintf’ keyword is used to add data. The only difference is we open our data file in append mode i.e. ‘a’. This allows user to add record at the end of the existing records in a data file. If there is no existing data file with the mentioned name then new will be created and records are stored from the beginning of the file.

Program example to add one record in existing data file “library.txt”
#include 
int main()
{
   char name[10];
   float price;
   int id;
   FILE *fptr;
   fptr = fopen(“library.txt” , ”a”); // opens data file in append mode
   printf("Enter book id name and price”);
   scanf(“%d %s %f”, &id, name ,&price); // stores id name and price in main memory
   fprintf(fptr,“%d %s %f”,id, name ,price); // stores id name and price in secondary memory
   fclose(fptr);
   return 0;
}

The above program stores only add one record at the end of the existing data file “library.txt”. 

Click here to for C program Table of Content (Main Menu)