File Handling

The entire data is lost when either the program is terminated or the computer is turned off. It is, therefore, necessary to have a more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. The method employs the concept of files to store data.

Type of File

  1. Text
  2. Binary

File Operations

  1. Creating and Opening a new file
  2. Closing a file
  3. Read and write

Working with files

When working with file, you need to declare a pointer of type FILE(data type). This declaration is needed for communication between the file and program.

		FILE *fp;

Creating and opening a file

Opening and creating(new) of a file is performed using the library function fopen() whose declaration is done in “stdio.h” header file.

The syntax for opening a file is:

		fp = fopen("file_name","mode")
Modes in File Handling For Text-File
File Mode Meaning of Mode
r Open for reading.
w Open for writing.
a Open for append. i.e, Data is added to end of file.
r+ Open for both reading and writing.
w+ Open for both reading and writing.
a+ Open for both reading and appending.

 

Modes in File Handling For Binary-File
File Mode Meaning of Mode
rb Open for reading in binary mode.
wb Open for writing in binary mode.
ab Open for append in binary mode. i.e, Data is added to end of file.
rb+ Open for both reading and writing in binary mode.
wb+ Open for both reading and writing in binary mode.
ab+ Open for both reading and appending in binary mode.

Note:-Let’s suppose the file new_file.txt doesn’t exist in the location . The first function creates a new file named new_file.txt and opens it for writing as per the mode ‘w’.

The writing mode allows you to create and edit (overwrite) the contents of the file.

Closing a File

Closing a file is performed using library function fclose() also declared in stdio.h header file.

The Synatx for closing the file is:-

	
		fclose(fp);

Read and write operation to a text file

For read and write to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE.

For Example Write to a text file using fprintf()

C Code Example

#include <stdio.h>
#include<stdlib.h>
void main()
{
   int number;
   FILE *fp;
   fp = fopen("new_file.txt","w");

   if(fp == NULL)
   {
      printf("Error!");   
      exit(1); 
   }

   printf("Enter any number: ");
   scanf("%d",&number);

   fprintf(fp,"%d",number);
   fclose(fp);
}

This program takes a number from user and stores in the file new_file.txt.

For Example Read from a text file using fscanf()

C Code Example

#include <stdio.h>
#include<stdlib.h>
void main()
{
   int number;
   FILE *fp;

   if ((fp = fopen("new_file.txt","r")) == NULL){
       printf("Error! opening file");

    //Program exits if the file pointer returns NULL
       exit(1);
   }

   fscanf(fp,"%d", &number);

   printf("Value of number =%d", number);
   fclose(fp); 
  
  
}

Read and write operation to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case of binary files.

Write operation to a binary file

	fwrite(address_data, size_data, numbers_data, pointer_to_file);

For example writing to a binary file using fwrite():-

C Code Example

#include <stdio.h>
#include<stdlib.h>
struct number
{
   int n1, n2;
};

void main()
{
   int a;
   struct number n;
   FILE *fp;

   if ((fp = fopen("new_file.bin","wb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   for(a = 1; a < 5; ++a)
   {
      n.n1 = a;
      n.n2 = 2a;
      n.n3 = 3a;
      fwrite(&num, sizeof(struct number), 1, fp); 
   }
   fclose(fp); 
  
   
}

Read operation from a binary file

	fread(address_data, size_data, numbers_data, pointer_to_file);

For example reading from a binary file using fread():-

C Code Example

#include <stdio.h>
#include<stdlib.h>
struct number
{
   int n1, n2, n3;
};

void main()
{
   int a;
   struct number n;
   FILE *fp;

   if ((fp = fopen("new_file.bin","rb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   for(a = 1; a < 5; ++a)
   {
      fread(&n, sizeof(struct number), 1, fp); 
      printf("a1: %d\ta2: %d\ta3: %d", n.n1, n.n2, n.n3);
   }
   fclose(fp); 
  
   
}

Getting data using fseek()

If you have many records inside a file and need to access a record at a specific position,you can find easily with help of a fseek()

The Syntax of fseek() :-

	fseek(FILE * stream, long int offset, int whence)
  1. stream − This is the pointer to a FILE object that identifies the stream.
  2. offset − This is the number of bytes to offset from whence.
  3. whence − This is the position from where offset is added. It is specified by one of the following constants :-
Whence Meaning
SEEK_SET Starts the offset from the beginning of the file.
SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location of the cursor in the file.