Table of contents
1.
Introduction 
2.
Functions for file handling
3.
Opening a File
4.
Reading from a file
5.
Writing a File
6.
Closing a File
7.
Deleting a file
8.
Read and Write the Data to a Text File
9.
Read and Write the Data to a Binary File
10.
FAQs
11.
Key takeaways
Last Updated: Mar 27, 2024

Introduction of File Handling

Author Shivam Verma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

In the C programming language, File handling refers to the task of storing data in the C program in the form of input or output produced by running C programs in data files, i.e., a binary file or a text file for future reference and analysis.

The operations that we can perform on a File in C are: 

  • Creation of the new file.
  • Opening an existing file.
  • Reading from the file.
  • Writing to the file.
  • Deleting the file.

Recommended Topic, Sum of Digits in C, C Static Function

Functions for file handling

Many functions in the C library are used to open, store, read, search or close files. There are some file functions are given below:

  1. fopen(): We use this function to open a new or existing file. The syntax of the fopen() is:
    *fptr = FILE *fopen(const char *filename, const char *mode);
     
  2. fclose(): We use this function to close a file. The syntax of the fclose() is:
    int fclose( FILE *fptr);
     
  3. fgetc(): We use this function to read a single character from a given file and then increments the file position indicator. The syntax of the fgetc() is:
    int fgetc(FILE *fptr);
     
  4. fputc(): We use this function to write a character to the specified file at the current position and then increments the file position indicator. The syntax of the fputc() is:
    int fputc(int c, FILE *fptr);
     
  5. fgets(): We use this function to read characters from a file. The syntax of the fgets() is:
    char *fgets(char *str, int n, FILE *fptr) 
     
  6. fputs(): We use this function to write a string of characters to a file at the location indicated by the file pointer. The syntax of the fputs() is:
    Int fputs(const char *str, FILE *fptr) 
     
  7. fprintf(): We use this function to print formatted output into the file. The syntax of the fprintf() is:
    fprintf(FILE *fptr, const char *format[,arguments,...]);
     
  8. fscanf(): We use this function to print formatted output into the file. The syntax of the fscanf() is:
    fscanf(FILE *fptr, const char *format[,address,...]);
     
  9. ftell(): The ftell() function gives the current position of the file position pointer. The value is counted from the beginning of the file. The syntax of the ftell() is:
    long ftell(FILE *fptr);
     
  10. rewind(): We use this function to set the file position pointer to the beginning of the file. The syntax of the rewind() is:
    rewind(FILE *fptr);
     
  11. fseek(): We use this function to set the file pointer to the given position. The syntax of the fseek() is:
    int fseek(FILE *fptr, long displacement, int origin);
     
  12. remove(): We use this function to delete the file. The syntax of the remove() is:
    int remove(const char *filename)
    Also read -  File Handling in CPP

Opening a File

Establishing a connection between the program and the file is called opening the file. Opening a file is performed using the fopen() function defined in the stdio.h header file. The syntax of the fopen() is:

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

Here in the above syntax, *fptr is the pointer to the file that establishes a connection between the file and the program, *filename is the name of the file to be opened, and *mode decides which operations(read, write, append, etc.) are to be performed on the file.

There are the following modes for opening a file:

You can also read about the jump statement and Floyd's Triangle in C

Reading from a file

To read the file, we have to open it first using any of the modes. For example, if we only want to read the file, open it in "r" mode. On the basis of the mode selected during file opening, we are allowed to perform certain operations on the file. There are some functions dedicated to reading data from a file:

  • fgetc()
  • fgets()
  • fscanf()

Writing a File

To write the file, we have to open it first using "w" mode. In C, newline characters' \n' must be explicitly added when we write to a file.

There are some functions dedicated to writing data into a file:

  • fputc()
  • fputs()
  • fprintf()

Closing a File

The file that was opened using the fopen() function must be closed when no more operations are performed. We use the fclose() function for closing a file. The syntax of the fclose() is:

int fclose( FILE *fptr);

Here in the above syntax, the fptr is a file pointer associated with the file to be closed. After closing the file, the connection between the file pointer and the file is broken. Now the file pointer fptr is free to connect to another file.

Deleting a file

We use the remove() function in C language to delete a file. It returns 0 if the deletion operation is successfully completed. Otherwise, a non-zero return on failure.

Syntax:

remove ("filename");

Here in the above syntax, The remove() function accepts one parameter: the name of the file that is to be deleted.

Here is a C program that illustrates the use of remove() to delete a text file:

#include<stdio.h>
int main()
{
    if (remove("test.txt")==0)
    {
        printf("The file is deleted successfully");
    }
    else
    {
        printf("Unable to delete the file");
    }
   return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Unable to delete the file


You can also read about C dynamic array.

Read and Write the Data to a Text File

We use the functions fprintf() and fscanf() for writing and reading to a text file. These functions are the file versions of the printf() and scanf(). But there is a major difference, i.e., both fscanf() and fprintf() expect a pointer pointing towards the structure FILE in the program.

Here is a C program that illustrates the use of fprintf() to write a text file:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int data;
   FILE *fptr;
   fptr = fopen("C:\\test.txt","w");
   if(fptr==NULL)
   {
      printf("Error in opening file\n");   
      exit(1);             
   }
   printf("Enter some data: ");
   scanf("%d",&data);
   fprintf(fptr,"%d",data);
   fclose(fptr);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

The program mentioned above takes an integer number from the user and stores it in the file test.txt. Once you compile and run this program, you can see a text file test.txt created in the C drive of your computer. When you open the test text file, you will see what integer you entered as an input while coding.

Here is a C program that illustrates the use of fscanf() to read a text file:

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int data;
   FILE *fptr;
   if ((fptr=fopen("C:\\test.txt","r"))==NULL)
   {
       printf("Error in opening file\n");
       exit(1);
   }
   fscanf(fptr,"%d",&data);
   printf("The value of n is %d", data);
   fclose(fptr); 
   return 0;
}
You can also try this code with Online C Compiler
Run Code

The program mentioned above reads the integer present in the test.txt file and then prints this integer as an output on the computer screen.

Read and Write the Data to a Binary File

We use the functions fwrite() and fread() for writing and reading to a binary file.

The syntax of fwrite() function is:

fwrite(const void *ptr, size_t size, size_t n, FILE *fptr);

The syntax of fread() function is:

fread(void *ptr, size_t size, size_t n, FILE *fptr);

Here in the above syntaxes, ptr is a pointer which points to the block of memory that contains the information to be written to the file, size denotes the length of an item in bytes, n is the number of items to be written to the file, and fptr is a FILE pointer.

Here is a C program that illustrates the use of fwrite() to write a binary file in C: 

#include <stdio.h>
#include <stdlib.h>
struct Numbers
{
   int num1;
   int num2;
   int num3;
};
int main()
{
   int i;
   struct Numbers nums;
   FILE *fptr;
   if((fptr=fopen("C:\\test.bin","wb"))==NULL)
   {
       printf("Error in opening file");
       exit(1);
   }
   for(i=0;i<4;i++)
   {
      nums.num1 = i;
      nums.num2 = 6*i;
      nums.num3 = 8*i+2;
      fwrite(&nums, sizeof(nums), 1, fptr); 
   }
   fclose(fptr); 
   return 0;
}
You can also try this code with Online C Compiler
Run Code

In the above program, we create a new file test.bin in the C drive of our computer. We declare a structure 'Numbers' with three numbers- num1, num2, and num3, and define it in the main function as nums. We store the values into the file using the fwrite() function inside the for loop.

Here is a C program that illustrates the use of fread() to read a binary file in C:

#include <stdio.h>
#include <stdlib.h>
struct Numbers
{
   int num1;
   int num2;
   int num3;
};
int main()
{
   int i;
   struct Numbers nums;
   FILE *fptr;
   if((fptr=fopen("C:\\test.bin","wb"))==NULL)
   {
       printf("Error in opening file");
       exit(1);
   }
   while(fread(&nums, sizeof(nums), 1, fptr)==1)
   {
       printf("num1: %d\tnum2: %d\tnum3: %d\n", nums.num1, nums.num2, nums.num3);
   }
   fclose(fptr); 
   return 0;
}
You can also try this code with Online C Compiler
Run Code

We read the same file test.bin using the fread() function in the above program. The fread() function returns 1 till there are numbers in the file and returns a number less than 1 when there is no record.

Also see, Tribonacci Series and Short int in C Programming

FAQs

  1. What is Files in C and its Uses?
    Ans: The file is a collection of data that occupies some space in the computer's secondary storage. A file is generally used as a real-life application that contains a large amount of data.
     
  2. What is the use of file handling in C?
    Ans: The File handling Concept is generally used to read, store, update, delete data on a file. This file is generally in .txt format and permanently stored on a secondary storage device.
     
  3. What is the syntax for opening a file?
    Ans: FILE *fopen(const *filename, const char *mode) is the syntax for opening a file. Here in the syntax filename is the file's name and mode in which the file is to be opened.

Key takeaways

In this article, we have extensively discussed the File handling concept in the C language. We also discussed the various operations associated with data files with the help of illustrative programs. We hope that this blog has helped you enhance your knowledge regarding File handling and if you would like to learn more, check out our article on Exception Handling. You can read other C language articles by clicking here. Do upvote our blog to help ninjas grow. Happy Coding!

Live masterclass