• C Programming Video Tutorials

File Handling in C



All the IO devices are treated as files in C language. As C doesn’t have any keywords to perform I/O operations, it uses the library functions defined in the header files. For example, the functions scanf() and printf() respectively read data from the stdin file and write data to the stdout file. Instead of standard IO devices, you often need to read/save data from or to persistent computer files.

In this chapter, we will explain how to use the File IO functions in C. We will see some basic file-handling operations in C. The operations are listed below −

  • Opening a File
  • Writing into a File
  • Reading from File
  • Appending in a File

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high-level functions as well as low-level (OS level) calls to handle files on your storage devices. This chapter will take you through the important calls for file management.

Opening a New or an Existing File

To perform read/write operations, you need to open the file with permission to perform the respective operation. The "stdio.h" head file defines a fopen() function that returns the FILE pointer to the disk file.

FILE *fopen( const char * filename, const char * mode );

Here, filename is a string literal, which you will use to name your file. The access mode can have one of the following values −

Mode Description
r Opens an existing text file for reading purposes.
w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
r+ Opens a text file for both reading and writing.
Opens a text file for both reading and writing. It first truncates 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 the file if it does not exist. The reading will start from the beginning but writing can only be appended.

The fopen() function returns a pointer of the FILE type. FILE is a predefined struct type in "stdio.h" and contains attributes such as the file descriptor, size, and position, etc.

typedef struct {
   int fd;			/* File descriptor */
   unsigned char *buf;	/* Buffer */
   size_t size;		/* Size of the file */
   size_t pos;		/* Current position in the file */
} FILE;

Types of Files

There are two types of files: text files and binary files.

Text file − A text file contains data in the form of ASCII characters and is generally used to store a stream of characters. Each line in a text file ends with a new line character ("\n"), and generally has a ".txt" extension.

Binary file − A binary file contains data in raw bits (0 and 1). Different application programs have different ways to represent bits and bytes and use different file formats. The image files (.png, .jpg), the executable files (.exe, .com), etc. are the examples of binary files.

The file access modes by default open the file in the text or ASCII mode. If you are going to handle binary files, then you will use the following access modes instead of the above-mentioned ones:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File

To close a file, use the fclose() function. The prototype of this function is −

int fclose(FILE *fp);

The fclose() function returns zero on success, or EOF if there is an error in closing the file.

The fclose() function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.

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

File IO Functions

The stdio.h header file provides different library functions that handle read/write operations. They are listed below −

  • Formatted file IO: fscanf() and fprintf()
  • Unformatted character File IO: fgetc() and fputc()
  • Unformatted string File IO: fgets() and fputs()
  • Binary File IO : fread() and fwrite()

Writing into a File

The following library functions are provided to write data in a file opened in writeable mode −

  • fputc() : writes a single character
  • fgets(): writes a string
  • fprintf(): writes a formatted data

The fputc() Function

The function fputc() is an unformatted function that writes a single character value of the argument "c" to the output stream referenced by "fp".

int fputc(int c, FILE *fp);

Example

In the following code, one character from a given char array is written into a file opened in the "w" mode:

#include <stdio.h>

int main() {

   FILE *fp;
   char * string = "C Programming tutorial from TutorialsPoint";
   int i;
   char ch;

   fp = fopen("file1.txt", "w");

   for (i = 0; i < strlen(string); i++) {
      ch = string[i];
      if (ch == EOF)
         break;
      fputc(ch, fp);
   }
   printf ("\n");
   fclose(fp);
   
   return 0;
}

Output

After executing the program, "file1.txt" will be created in the current folder and the string is written to it.

The fputs() Function

The function fputs() writes the string "s" to the output stream referenced by "fp". It returns a non-negative value on success, else EOF is returned in case of any error.

int fputs(const char *s, FILE *fp);

Example

The following program writes strings from the given two-dimensional char array to a file −

#include <stdio.h>

int main() {

   FILE *fp;
   char *sub[] = {"C Programming Tutorial\n", "C++ Tutorial\n", "Python Tutorial\n", "Java Tutorial\n"};
   fp = fopen("file2.txt", "w");

   for (int i = 0; i < 4; i++) {
      fputs(sub[i], fp);
   }

   fclose(fp);
   
   return 0;
}

Output

When the program is run, a file named "file2.txt" is created in the current folder and save the following lines −

C Programming Tutorial
C++ Tutorial
Python Tutorial
Java Tutorial

The fprintf() Function

The fprintf() function sends a formatted stream of data to the disk file represented by the FILE pointer.

int fprintf(FILE *stream, const char *format [, argument, ...])

Example

In the following program, we have an array of struct type called "employee". The structure has a string, an integer, and a float element. Using the fprintf() function, the data is written to a file.

#include <stdio.h>

struct employee {
   int age;
   float percent;
   char *name;
};

int main() {

   FILE *fp;
   struct employee emp[] = {
      {25, 65.5, "Ravi"}, 
      {21, 75.5, "Roshan"}, 
      {24, 60.5, "Reena"}
   };

   char *string;
   fp = fopen("file3.txt", "w");

   for (int i = 0; i < 3; i++) {
      fprintf(fp, "%d %f %s\n", emp[i].age, emp[i].percent, emp[i].name);
   }
   fclose(fp);
   
   return 0;
}

Output

When the above program is executed, a text file is created with the name "file3.txt" that stores the employee data from the struct array.

Reading a File

The following library functions are provided to read data from a file that is opened in read mode −

  • fgetc(): reads a single character
  • fgets(): reads a string
  • fscanf(): reads a formatted data

The fgetc() Function

The fgetc() function reads a character from the input file referenced by "fp". The return value is the character read, or in case of any error, it returns EOF.

int fgetc(FILE * fp);

Example

The following example reads the given file in a character by character manner till it reaches the end of file.

#include <stdio.h>

int main(){

   FILE *fp ;
   char ch ;
   fp = fopen ("file1.txt", "r");

   while(1) {
      ch = fgetc (fp);
      if (ch == EOF)
         break;
      printf ("%c", ch);
   }
   printf ("\n");
   fclose (fp);
}

Output

Run the code and check its output −

C Programming tutorial from TutorialsPoint

The fgets() Function

The function fgets() reads up to "n − 1" characters from the input stream referenced by "fp". It copies the read string into the buffer "buf", appending a null character to terminate the string.

Example

This following program reads each line in the given file till the end of the file is detected −

# include <stdio.h>

int main() {

   FILE *fp;
   char *string;
   fp = fopen ("file2.txt", "r");

   while (!feof(fp)) {
      fgets(string, 256, fp);
      printf ("%s", string) ;
   }
   fclose (fp);
}

Output

Run the code and check its output −

C Programming Tutorial
C++ Tutorial
Python Tutorial
Java Tutorial

The fscanf() Function

The fscanf() function in C programming language is used to read formatted input from a file.

int fscanf(FILE *stream, const char *format, ...)

Example

In the following program, we use the fscanf() function to read the formatted data in different types of variables. Usual format specifiers are used to indicate the field types (%d, %f, %s, etc.)

#include <stdio.h>

int main() {

   FILE *fp;
   char *s;
   int i, a;  
   float p;

   fp = fopen ("file3.txt", "r");

   if (fp == NULL) {
      puts ("Cannot open file"); return 0;
   }

   while (fscanf(fp, "%d %f %s", &a, &p, s) != EOF)
   printf ("Name: %s Age: %d Percent: %f\n", s, a, p);
   fclose(fp);

   return 0;
}

Output

When the above program is executed, it opens the text file "file3.txt" and prints its contents on the screen. After running the code, you will get an output like this −

Name: Ravi Age: 25 Percent: 65.500000
Name: Roshan Age: 21 Percent: 75.500000
Name: Reena Age: 24 Percent: 60.500000

Binary I/O Functions

The read/write operations are done in a binary form in the case of a binary file. You need to include the character "b" in the access mode ("wb" for writing a binary file, "rb" for reading a binary file).

There are two functions that can be used for binary input and output: the fread() function and the fwrite() function. Both of these functions should be used to read or write blocks of memories, usually arrays or structures.

The fwrite() Function

The fwrite() function writes a specified chunk of bytes from a buffer to a file opened in binary write mode. Here is the prototype to use this function:

fwrite(*buffer, size, no, FILE);

Example

In the following program, an array of a struct type called "employee" has been declared. We use the fwrite() function to write one block of byte, equivalent to the size of one employee data, in a file that is opened in "wb" mode.

#include <stdio.h>

struct employee {
   int age;
   float percent;
   char name[10];
};

int main() {

   FILE *fp;
   struct employee e[] = {
      {25, 65.5, "Ravi"}, 
      {21, 75.5, "Roshan"}, 
      {24, 60.5, "Reena"}
   };

   char *string;

   fp = fopen("file4.dat", "wb");
   for (int i = 0; i < 3; i++) {
      fwrite(&e[i], sizeof (struct employee), 1, fp);
   }

   fclose(fp);
   
   return 0;
}
Output
When the above program is run, the given file will be created in the current folder. It will not show the actual data, because the file is in binary mode.

The fread() Function

The fread() function reads a specified chunk of bytes from a file opened in binary read mode to a buffer of the specified size. Here is the prototype to use this function:

fread(*buffer, size, no, FILE);

Example

In the following program, an array of a struct type called "employee" has been declared. We use the fread() function to read one block of byte, equivalent to the size of one employee data, in a file that is opened in "rb" mode.

#include <stdio.h>

struct employee {
   int age;
   float percent;
   char name[10];
};

int main() {

   FILE *fp;
   struct employee e;

   fp = fopen ("file4.dat", "rb");

   if (fp == NULL) {
      puts ("Cannot open file"); 
      return 0;
   }

   while (fread (&e, sizeof (struct employee), 1, fp) == 1)
   printf ("Name: %s Age: %d Percent: %f\n", e.name, e.age, e.percent);

   fclose(fp);
   
   return 0;
}
Output

When the above program is executed, it opens the file "file4.dat" and prints its contents on the screen. After running the code, you will get an output like this −

Name: Ravi Age: 25 Percent: 65.500000
Name: Roshan Age: 21 Percent: 75.500000
Name: Reena Age: 24 Percent: 60.500000
Advertisements