Skip to main content

29. File Handling in C

 

Why do we need File

Files are used to store data and information. Files are used to read and access data anytime from the hard disk. Files make it easy for a programmer to access and store content without loosing it on program termination.

When a C program is terminated, the data stored in RAM is lost. Storing in a file will preserve our data even after the program terminates. RAM is not able to handle quite large amount of data due to its small size relative to the hard disk. It is easy to transfer data as files.

Volatile and Non-Volatile Memory

Volatile MemoryNon-Volatile Memory
Volatile memory is computer storage that only maintains its data while the device is powered.Non-Volatile memory is computer memory that can retain the stored information even when not powered.
The RAM will hold data, programs and information as long as it has a constant power supply but immediately the power is interrupted all that content is cleared.This type of memory is also referred to as permanent memory since data stored within it can be retrived even when there is no constant power supply.
The volatile memory will only hold data temporarily.It is used for the long-term storage of data.

File Operations in C

In C we can perform these high level operations on files:

  • Creating a new file
  • Opening a file
  • Closing a file
  • Reading from and writing to a file

Working with Files

When working with files, we have to declare a pointer of type FILE. This declaration helps us to work with files through C program.

Opening a file: Creating or Editing a file

  • stdio.h contains a function called fopen() for opening files in C.
  • The syntax for opening a file in standard I/O is:
    ptr = fopen("file_name", "mode");
  • For example:
    fopen("S:\\C Tutorial\\29.txt", "w");

Closing a file

  • Any file which is opened in a C program needs to be closed.
  • Closing a file is accomplished by the library function fclose().
  • fclose(fptr); // fptr is the file pointer associated with file to be closed.

Mode and Description

ModeDescription
rOpens a existing text file for reading.
wOpens a file for writing. If it doesn't exist, then a new file will be created. Writing starts from beginning of the file.
aOpens a text file for writing in append mode. If it does not exist, then a new file will be created. The program will start appending content to the existing file content.
r+This mode will open a text file for both reading and writing. It replaces the first characters in the file which are to be inserted.
w+Opens a text file for both reading and writing. It first reduces the file to zero length if it exists, otherwise creates a file if it does not exist.
a+Opens a text file for both reading and writing. It creates a new file if it does not exist. The reading will start from the beginning but writing can only append to file.

Reading a file

  • In order to read a file, we can use fscanf() function.
  • This function is file version of scanf() function.
  • fscanf() expects a file pointer in addition to the other arguments which scanf() expects.
  • We will have to open the file in read mode in order to use this function.

myfile.txt :

This file is created by Deepak.
We can store permanent information, data using files.
This is some content in this file.

C program :

#include <stdio.h>
int main()
{
   FILE *a = NULL;
   char b[30];
   a = fopen("myfile.txt", "r"); // Read mode
   fscanf(a, "%s", b);
   printf("%s\n", b);
   fclose(a);
   return 0;
}

Output :

This

Writing a file

  • In order to write to a file, we can use fprintf() function.
  • This function is file version of printf() function.
  • fprintf() expects a file pointer in addition to the other arguments which printf expects.
  • We will have to open a file in write mode in order to use this function.

myfile.txt before running C code:

This file is created by Deepak.
We can store permanent information, data using files.
This is some content in this file.

C program :

#include <stdio.h>
int main()
{
   FILE *a = NULL;
   char b[50] = "This content is from a string.";
   a = fopen("myfile.txt", "w"); // Write mode
   fprintf(a, "%s", b);
   fclose(a);
   return 0;
}

myfile.txt after running C code :

This content is from a string.

myfile.txt before running C code:

This file is created by Deepak.
We can store permanent information, data using files.
This is some content in this file.

C program :

#include <stdio.h>
int main()
{
   FILE *a = NULL;
   char b[50] = "This content is from a string.";
   a = fopen("myfile.txt", "a"); // Append mode
   fprintf(a, "%s", b);
   fclose(a);
   return 0;
}

myfile.txt after running C code :

This file is created by Deepak.
We can store permanent information, data using files.
This is some content in this file.
This content is from a string.

Other file I/O functions in C

there are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.

Some of them are:

  • fputc
  • fputs
  • fgetc
  • fgets

fputc function in C

Simplest function to write characters to a file is fputc. Syntax of fputc is

int fputc(character, FILE pointer);

It returns the written character on success. On failure it returns EOF (end of file character). The EOF is a constant defined in the header file stdio.h.

fputs function in C

fputs function is used to write a null terminated string to a file in C. The syntax of fputs is

int fputs(string name, FILE pointer);

fgetc function in C

Simplest function to read characters to a file is fputc. Syntax of fputc is

int fgetc(FILE pointer);

It returns the read character on success. On failure it returns EOF (end of file character). The EOF is a constant defined in the header file stdio.h.

fgets function in C

fgets function is used to read a null terminated string to a file in C. The syntax of fgets is

int fgets(string name, int (number_of_characters + 1), FILE pointer);

Comments