File Handling in C

In this section of the tutorial, we will discuss about File Handling in C. Previously, we have been using console oriented Input/Output function system that is implemented through library functions i.e. scanf() and printf(), to read and write data from the user.

All files are closed automatically when your program terminates normally, either by main( ) returning to the operating system or by a call to exit( ). Files are not closed when a program terminates abnormally, such as when it crashes or when it calls abort( ).

We will learn about the total management of files in C in this tutorial in detail.

How Handle files in C?

In the whole major topics of the C tutorial, we have used the function scanf() and printf() read data from the user and to display the output on the screen respectively.

  • These functions are known as console oriented input/output functions.
  • They have some limitations as they can only be used for small data.
  • They cannot handle operations of large amounts of data.
  • They are not ideal to be used for real-life problems.

Two of the main problems these console functions possess are that they are very time consuming for handling a large amount of data and the entire data is destroyed/lost as soon as the program is closed or the machine is turned off.

Here comes the use of File Handling in C. It is used because it provides functions and approaches to save data on a computer permanently that does not get destroys even if the computer is turned off.

How can we read/write data in C?

C programming language provides a flexible approach to handle data operations. These operations include reading of data and writing of data in a program and permanently saving it on the storage disk after the program termination or shutting down the computer.

  • It reduces the reading/writing time of data in the program and doesn’t let the data to be destroyed.
  • It provides operation on large volumes of data.
  • It helps in making the use of program and data combination to the maximum potential.

What are the file operations?

In C, a file may be anything from a disk file to a terminal or printer. We associate a stream with a specific file by performing an open operation. Once a file is open, information can be exchanged between it and your program.

Not all files have the same capabilities. For example, a disk file can support random access, while some printers cannot. This brings up an important point about the C I/O system: All streams are the same, but all files are not.

So here comes the need of having purpose specific function that provides the ability to perform different operations on a file.

C programming language supports many such functions that are frequently used in file handling operations, that are:

  • Naming a file.
  • Opening a file.
  • Reading data from a file.
  • Writing data to a file.
  • Closing a file.

Below is a table of different high-level functions with their operations.

Function name

Operation
fopen()

Creates a new file

Or opens an existing file for use.

fclose()

Closes a file.
fgetc()

Reads a character from file.

fputc()

Writes a character from file.

fprintf()

Writes a data from file.

fscanf()

Reads a data from file.

fgetw()

Reads an integer .
fputw()

Writes an integer.

fseek()

Sets a position to a desired points in the file.
ftell()

Gives the current position in the file(i.e number of bytes from the beginning).

rewind()

Sets the position to the beginning of the file.
fwrite()

Writes data to a file.

fread()

Reads data from a file.
feof()

Tests if end-of-file has been reached.

fflush()

Flushes a stream.
Remove()

Deletes the specified file.

Rename()

Changes the name or path of file.
ferror()

Tests if an error has occurred in the file.

Further, we will discuss how to we can define, open, and read a file using these file handling functions.

How to define a file in C?

We must define a file before we operate any file handling function on it to store data in the file. It has three parts, i.e. Filename, Data Structure, and Purpose.

Filename is a string of characters that has two parts, i.e. primary name and optional period with the extension.

Example:

Input.data
store
PROG.C
Student.c
Text.out

Data Structure of a file is defined as FILE in the library of standard input/output function definitions. All files must be declared as type FILE before they are used. FILE is a defined data type.

The general form of declaring and opening a file is:

FILE *fp;
fp = fopen (“filename”, “mode”);

  • Here, variable fp is declared as a pointer to data type FILE.
  • In the last statement, filename file is opened and an identifier is assigned to the FILE type pointer fp.
  • This pointer fp contains all the file’s information which is used as a communication link between the computer and the program.

We will discuss about opening a declared file in detail under the next heading.

How to open a file in C?

Before we can read or write information from or to a file on the hard disk we must open the file.

To open the file function fopen( ) is used and a mode which tells the compiler that we would write, read or modify the file. This fopen( ) function performs three tasks:

  • Searches the file on the disk.
  • Then it loads the file from the disk into the place in memory called buffer.
  • It sets a character pointer which will point the first character in the buffer.

What is the buffer?

The buffer is the temporary area in the memory of the computer where a file is kept for some time so that it can be accessed quickly to read or write characters.

Whenever we open a file the contents of the file get copied to this temporary area and then read character by character from the buffer rather than from the disk and similarly to write characters of the file one at a time on the disk would also be a wastage of time so the buffer is used to write the characters and then they are transferred to the disk.

The fopen() gathers information like file name, size of the file, and the mode to open the file then returns the address of this file to a file pointer called fp.

This can be explained as:

FILE *fp;
fp=fopen(“file_name”,”mode”);

  • Here, FILE is a constant defined in the header file stdio.h.
  • It is compulsory to use #include<stdio.h>.

Modes are specified as strings that serve the purpose of opening the file. In many C compilers, there are different modes of operations used to open a file, that are:

Mode

Meaning

r

Open a text file for reading
w

Create a text file for writing

a

Append to a text file
rb

Open a binary file for reading

wb

Create a binary file for writing
ab

Append to a binary file

r+

Open a text file for read/write
w+

Create a text file for read/write

a+

Append or create a text file for read/write
r+b

Open a binary file for read/write

w+b

Create a binary file for read/write
a+b

Append or create a binary file for read/write

How to read a file?

Function fscanf()

The function fscanf(0 is used to read a group of mixed data simultaneously.

fscanf() is used as:

fscanf (fp, “control string”, list);

  • Here, the above statement will read the list of items from the file specified by fp, in order to the specifications contained in the control string.

Example:

fscanf(f2, “%s %d”, item, &quantity);

  • Here, function fscanf() returns the number of items that are successfully read.
  • When the end of the file is reached, it returns the value EOF.

Below is an example to demonstrate the use of Function fscanf() for reading mixed data type values.

Example:

C Program to read mixed data type values in a file using Function fscanf().

Code:

#include<stdio.h>
int main()
{
    FILE *fp;
    int number,quantity,i;
    float price,value;
    char item[10],filename[10];

    printf("Enter file name: \n");
    scanf("%s",filename);
    fp = fopen(filename,"w");
    printf("Enter stock data: \n");
    printf("Item  Code  Quantity  Price\n");
    for(i=1;i<=3;i++)
    {
        fscanf(stdin,"%s %d %d %f",&item,&number,&quantity,&price);
        fprintf(fp,"%s  %d  %d  %.2f",item,number,quantity,price);
    }
    fclose(fp);
    fprintf(stdout,"\n\n");

    fp = fopen(filename,"r");

    printf("Item    Code    Quantity    Price       Value\n");
    for(i=1;i<=3;i++)
    {
        fscanf(fp,"%s %d %d %f %f",item,&number,&quantity,&price);
        value = price * quantity;
        fprintf(stdout,"%s  %7d  %8d      %8.2f %11.2f\n",item,number,quantity,price,value);
    }
    fclose(fp);
    return 0;
}

Output:

Enter file name: 
STOCKS
Enter stock data: 
Item  Code  Quantity  Price
a
1
10
100
b
2
20
200
c
3
30
300

Item    Code    Quantity    Price       Value
a        1        10        100.00     1000.00
b        2        20        200.00     4000.00
c        3        30        300.00     9000.00

Function getc()

The function getc( ) is used to read the contents of the file which has been brought to the buffer(partly or wholly) from the hard disk.

getc( ) is used as:

ch= getc(fp);

  • Here, getc( ) is used to read the character from the current position of the pointer.
  • The pointer now moves one place ahead so that it points to the next character.
  • The character which was read by the getc( ) is assigned to variable ch.

Below is an example to demonstrate the use of Function getc() for reading character data.

Example:

C Program to read character values in a file using Function getc().

Code:

#include<stdio.h>
int main()
{
    FILE *f1;
    char c;
    printf("INPUT\n");
    
    f1 = fopen("INPUT","w");

    while((c=getchar())!=EOF)
    {
        putc(c,f1);
    }
    fclose(f1);

    printf("OUTPUT\n");
    f1=fopen("INPUT","r");

    while((c=getc(f1))!=EOF)
    {
        printf("%c",c);
    }
    fclose(f1);
    return 0;
}

Output:

INPUT
WELCOME TO CODEDEC.
OUTPUT
WELCOME TO CODEDEC.

Function getw()

The function getw() is a integer-oriented function. It is similar to function getc() in attributes but it is only used to read integer values. This function is specifically used when we need to handle integer data.

The general form of this function is: getw(fp);

Below is an example to demonstrate the use of Function getw() for reading integer data.

Example:

C Program to read integer values in a file using Function getw().

Code:

#include<stdio.h>
int main()
{
    FILE *f1, *f2, *f3;
    int number,i;
    printf("Contents of file\n");
    f1 = fopen("DATA","w");
    for(i=1;i<=30;i++)
    {
        scanf("%d",&number);
        if(number==-1)
        {
            break;
        }
        putw(number,f1);
    }
    fclose(f1);
    f1 = fopen("DATA","r");
    f2 = fopen("ODD","w");
    f3 = fopen("EVEN","w");

    while((number = getw(f1))!=EOF)
    {
        if(number%2==0)
            putw(number,f3);
        else
            putw(number,f2);
    }
    fclose(f1);
    fclose(f2);
    fclose(f3);

    f2 = fopen("ODD","r");
    f3 = fopen("EVEN","r");

    printf("\nODD File");
        while((number=getw(f2))!=EOF)
            printf("%4d",number);
    printf("\nEVEN File");
        while((number=getw(f3))!=EOF)
            printf("%4d",number);
    fclose(f2);
    fclose(f3);
    return 0;
}

Output:

Contents of file
11
22
33
44
-55
00
-1

ODD File  11  33 -55
EVEN File  22  44   00

How to write data in a file in C?

Function fprintf()

This function is used to handle a group of mixed data simultaneously. Function fprintf() has an operation similar to that of function printf(), except that they work on files.

The general form of this function is:

fprintf(fp, “control string”, list);

  • Here, the first argument fp is a file pointer that specifies the file to be used for writing.
  • The control string contains output specifications for the items on the list.
  • The list may include variables, constants, and strings.

Example:

fprintf(f2, “%s %d %f”, name, age, 9.5);

  • Here, the name is an array of type char and age is a variable of type int.

Below is an example to demonstrate the use of Function fprintf() for writing mixed data type values.

Example: C Program to store mixed data type values in a file using Function fprintf().

Code:

#include<stdio.h>
int main()
{
    FILE *fp;
    int number,quantity,i;
    float price,value;
    char item[10],filename[10];

    printf("Enter file name: \n");
    scanf("%s",filename);
    fp = fopen(filename,"w");
    printf("Enter stock data: \n");
    printf("Item  Code  Quantity  Price\n");
    for(i=1;i<=3;i++)
    {
        fscanf(stdin,"%s %d %d %f",&item,&number,&quantity,&price);
        fprintf(fp,"%s  %d  %d  %.2f",item,number,quantity,price);
    }
    fclose(fp);
    fprintf(stdout,"\n\n");

    fp = fopen(filename,"r");

    printf("Item    Code    Quantity    Price       Value\n");
    for(i=1;i<=3;i++)
    {
        fscanf(fp,"%s %d %d %f %f",item,&number,&quantity,&price);
        value = price * quantity;
        fprintf(stdout,"%s  %7d  %8d      %8.2f %11.2f\n",item,number,quantity,price,value);
    }
    fclose(fp);
    return 0;
}

Output:

Enter file name: 
STOCKS
Enter stock data: 
Item  Code  Quantity  Price
a
1
10
100
b
2
20
200
c
3
30
300

Item    Code    Quantity    Price       Value
a        1        10        100.00     1000.00
b        2        20        200.00     4000.00
c        3        30        300.00     9000.00

Function putc()

Function putc( ) is used to print the characters from the screen to the file. And to print a string on the file the function puts( ) is used.

Example:

putc(ch,fp);

  • Here, ch is the name of the character and fp the file pointer.

putc(s,fp);

  • Here, s is the name of the string and fp the file pointer.

Below is an example to demonstrate the use of Function putc() for writing character data values.

Example: C Program to write character values in a file using Function putc().

Code:

#include<stdio.h>
int main()
{
    FILE *f1;
    char c;
    printf("INPUT\n");
    
    f1 = fopen("INPUT","w");

    while((c=getchar())!=EOF)
    {
        putc(c,f1);
    }
    fclose(f1);

    printf("OUTPUT\n");
    f1=fopen("INPUT","r");

    while((c=getc(f1))!=EOF)
    {
        printf("%c",c);
    }
    fclose(f1);
    return 0;
}

Output:

INPUT
THIS IS A TEST PROGRAM
OUTPUT
THIS IS A TEST PROGRAM

Function putw()

The function putw() is a integer-oriented function. It is similar to function putc() in attributes but it is only used to write integer values. This function is specifically used when we need to handle integer data.

The general form of this function is: putw(integer, fp);

Below is an example to demonstrate the use of Function putw() for writing integer data.

Example: C Program to write integer values in a file using Function putw().

Code:

#include<stdio.h>
int main()
{
    FILE *f1, *f2, *f3;
    int number,i;
    printf("Contents of file\n");
    f1 = fopen("DATA","w");
    for(i=1;i<=30;i++)
    {
        scanf("%d",&number);
        if(number==-1)
        {
            break;
        }
        putw(number,f1);
    }
    fclose(f1);
    f1 = fopen("DATA","r");
    f2 = fopen("ODD","w");
    f3 = fopen("EVEN","w");

    while((number = getw(f1))!=EOF)
    {
        if(number%2==0)
            putw(number,f3);
        else
            putw(number,f2);
    }
    fclose(f1);
    fclose(f2);
    fclose(f3);

    f2 = fopen("ODD","r");
    f3 = fopen("EVEN","r");

    printf("\nODD File");
        while((number=getw(f2))!=EOF)
            printf("%4d",number);
    printf("\nEVEN File");
        while((number=getw(f3))!=EOF)
            printf("%4d",number);
    fclose(f2);
    fclose(f3);
    return 0;
}

Output:

Contents of file
454
565
858
-998
-1

ODD File 565
EVEN File 454 858-998

How to close a file in C?

A file should be closed when all the operations have been finished. This is important to flush out all the information associated with the files from the buffers and to break all links to the file. It prevents any accidental misuse of the file.

Also, if we want to open a particular file in a different mode, then we must first close if it is already opened. When we have finished reading the file, we need to close it. This is done by function fclose( ).

The general form of the function used in closing a file is:

fclose (file_pointer);

This is used as:

fclose(fp);

  • Here, to close the file we do not need the filename.

The fclose( ) function performs three main tasks:

  • The characters in the buffer would be written to the file on the disk.
  • At the end of the file, a character with ASCII value 26 would get written.
  • The buffer gets eliminated from the file.

How to erase a file in C?

The could be a situation where we need to erase a file if it’s no longer in use. The remove( ) function erases that specified file.

The general form of this function is:

int remove(const char *filename);

  • It returns zero if successful. Otherwise, it returns a nonzero value.
  • The following program erases the file specified on the command line.
  • However, it first gives you a chance to change your mind.
  • A utility like this might be useful for new computer users.

How to access any file in C?

There could be a situation where we only want to access a particular part of a file and not the entire file. Here we can use a function called Function fseek().

The fseek() function is used in moving a file position to a desired location within the file.

The general form of this function is:

fseek(file_ptr, offset, position);

  • Here, file_ptr is a pointer to the file.
  • offset is a number or variable of long type.
  • position is an integer number.

The offset specifies the number of positions(bytes) to be moved from the location specified by the position.

The position may have one of the following values:

  1. Value = 0, indicates the beginning of the file.
  2. Value = 1, indicates the current position.
  3. Value = 2, indicates the end of the file.

The offset can also be positive, which indicates forward movement, or negative, which indicates backward movement. Also, function fseek() returns 0, after a successful operation.

Below is an example to demonstrate the use of Function fseek() for moving the file position.

Example: C Program to display the character positions in a file using Function fseek().

Code:

#include<stdio.h>
int main()
{
    FILE *fp;
    long n;
    char c;
    fp = fopen("RANDOM","w");
    while((c=getchar())!=EOF)
    {
        putc(c,fp);
    }
    printf("%ld characters entered\n",ftell(fp));
    fclose(fp);
    fp = fopen("RANDOM","r");
    n = 0L;

    while(feof(fp)==0)
    {
        fseek(fp,n,0);
        printf("Position of %c is %ld\n",getc(fp),ftell(fp));
        n = n+5L;
    }
    putchar('\n');

    fseek(fp,-1L,2);
    do
    {
        putchar(getc(fp));
    }
    while(!fseek(fp,-2L,1));
    fclose(fp);
    return 0;
}

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

26 characters entered

Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position of U is 20
Position of Z is 25
Position of � is 30

ZYXWVUTSRQPONMLKJIHGFEDCBA