File Handling in C with Examples

During programming, it is often required that we need to work with different types of file. C programming supports file handling and allows us to read and write files programmatically. In this article, we are going to demystify how file handling works in C with examples.

Concept of Data Files

We frequently use files for storing information which can be processed by our programs. Such files are called data files. A file is a bunch of bytes stored on some storage device.

Most of the application program processes a large volume of data which is permanently stored in data files. In order to store information permanently and retrieve, we need to use data files.

While developing software essential data is stored in data files or databases because data communication between the console unit and program is tedious and error-prone. Some of the problems which may occur while inputting data from console are:

  1. A lot of time is taken for data entry.
  2. Entire data would be re-entered if a mistake is made in input data.
  3. If the same data is to be processed later on, it would be entered afresh i.e. for every run, we require the same data entry.

So, to overcome above-mentioned problems we use data files which allows us to store and retrieve data in our program.

The FILE Pointer

As we know, we can have many files on our disk. While dealing with files, in our program, we need to specify which files we wish to use. In c programming, we use a new data type called file pointer to communicate with files.

Every file we open has its own file pointer variable. When we wish to read from a file or write to a file, we need to specify the file pointer variable. We can declare these file pointer variables as follows:

FILE Pointer Syntax

Syntax to declare file pointer variables in C programming is:

FILE *file_pointer1, *file_pointer2, *file_pointer3, ..., *file_pointerN;

FILE Pointer Example

  1. 
    FILE *fptr;
    
    Here fptr is file pointers and using fptr we can communicate with files.
  2. 
    FILE *source, *destination;
    
    Here source, destination are two file pointers.

Opening and Closing File

Opening Data File

A data file must be opened before it can be processed. Since files can be used in different ways i.e. for reading or writing to or both.

In C programming, the mode of file utilization is specified while opening the data file and library function fopen() defined in stdio.h is used to open a file.

fopen() Syntax

General syntax for fopen() is:


file_pointer_name = fopen("filename", "mode");

Here, filename represents the name of the file that we wish to use and mode specifies the purpose of opening the file i.e. reading (r), writing (w), appending (a), etc. File can be opened in text mode and binary mode. See Text File Modes , Binary File Modes & Text File Vs Binary Files.

fopen() function returns a pointer to the beginning of the file if it is successfully opened otherwise it returns NULL value which is defined in stdio.h

Function fopen() returns NULL if file can not be opened successfully otherwise it points to the file if it is opened successfully.

Closing Data Files

When the processing (reading,writing or both) is over in a file, it must be closed. The library function fclose() defined in stdio.h is used for this purpose.

fclose() Syntax

General syntax for fclose() is:


fclose(file_pointer_name);

Programming Examples

C program to read all contents from filename “tale.txt” using character I/O functions.

Consider tale.txt looks like:

A Tale of Two Cities by Charles Dickens
-----------------------------
Starting Paragraph
-----------------------------
It was the best of times, 
it was the worst of times, 
it was the age of wisdom, 
it was the age of foolishness, 
it was the epoch of belief, 
it was the epoch of incredulity, 
it was the season of Light, 
it was the season of Darkness, 
it was the spring of hope, 
it was the winter of despair, 
we had everything before us, 
we had nothing before us, 
we were all going direct to Heaven, 
we were all going direct the other way - in short, 
the period was so far like the present period, 
that some of its noisiest authorities insisted on its being received, 
for good or for evil, in the superlative degree of comparison only.

C Source Code: Reading File Contents


#include<stdio.h>
#include<stdlib.h>

int main()
{
 FILE *fptr;
 char ch;

 /* Opening file in read mode */
 fptr = fopen("tale.txt","r");
 if(fptr==NULL)
 {
  printf("Can't open file. Make sure file exits.\n");
  exit(1);
 }
 do
 {
  ch = fgetc(fptr);

  putchar(ch);

 }while(ch!=EOF);

 fclose(fptr);
 
 printf("\n\nProgram completed. Press any key to continue...");

 return 0;
}

Output

A Tale of Two Cities by Charles Dickens
-----------------------------
Starting Paragraph
-----------------------------
It was the best of times, 
it was the worst of times, 
it was the age of wisdom, 
it was the age of foolishness, 
it was the epoch of belief, 
it was the epoch of incredulity, 
it was the season of Light, 
it was the season of Darkness, 
it was the spring of hope, 
it was the winter of despair, 
we had everything before us, 
we had nothing before us, 
we were all going direct to Heaven, 
we were all going direct the other way - in short, 
the period was so far like the present period, 
that some of its noisiest authorities insisted on its being received, 
for good or for evil, in the superlative degree of comparison only.

Program completed. Press any key to continue...