Basics of File Handling in C - GeeksforGeeks

18 Oct, 2021
So far the operations using C program are done on a prompt / terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are:  
Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)Opening an existing file (fopen)Reading from file (fscanf or fgets)Writing to a file (fprintf or fputs)Moving to a specific location in a file (fseek, rewind)Closing a file (fclose)
Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
Opening an existing file (fopen)
Reading from file (fscanf or fgets)
Writing to a file (fprintf or fputs)
Moving to a specific location in a file (fseek, rewind)
Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.Functions in File Operations:  
Opening or creating file For opening a file, fopen function is used with the required access modes. Some of the commonly used file access modes are mentioned below.File opening modes in C:  
“r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
“rb” – Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
“w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
“wb” – Open for writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
“a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
“ab” – Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it will be created.
“r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
“rb+” – Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file.
“wb+” – Open for both reading and writing in binary mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
“ab+” – Open for both reading and appending in binary mode. If the file does not exist, it will be created.
As given above, if you want to perform operations on a binary file, then you have to append ‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use “a+b”. For performing the operations on the file, a special pointer called File pointer is used which is declared as  
FILE *filePointer; 

So, the file can be opened as 

filePointer = fopen(“fileName.txt”, “w”)
The second parameter can be changed to contain all the attributes listed in the above table. 
Reading from a file – The file read operations can be performed using functions fscanf or fgets. Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer. So, it depends on you if you want to read the file line by line or character by character.And the code snippet for reading a file is as:  
FILE * filePointer; 

filePointer = fopen(“fileName.txt”, “r”);

fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
Writing a file –:The file write operations can be performed by the functions fprintf and fputs with similarities to read operations. The snippet for writing to a file is as :  
FILE *filePointer ; 

filePointer = fopen(“fileName.txt”, “w”);

fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
Closing a file –: After every successful file operations, you must always close a file. For closing a file, you have to use fclose function. The snippet for closing a file is given as :  
FILE *filePointer ; 

filePointer= fopen(“fileName.txt”, “w”);

---------- Some file Operations -------

fclose(filePointer)
             Example 1: Program to Open a File, Write in it, And Close the File 
C
// C program to Open a File,// Write in it, And Close the File # include <stdio.h># include <string.h> int main( ){     // Declare the file pointer    FILE *filePointer ;         // Get the data to be written in file    char dataToBeWritten[50]        = "GeeksforGeeks-A Computer Science Portal for Geeks";     // Open the existing file GfgTest.c using fopen()    // in write mode using "w" attribute    filePointer = fopen("GfgTest.c", "w") ;         // Check if this filePointer is null    // which maybe if the file does not exist    if ( filePointer == NULL )    {        printf( "GfgTest.c file failed to open." ) ;    }    else    {                 printf("The file is now opened.\n") ;                 // Write the dataToBeWritten into the file        if ( strlen ( dataToBeWritten ) > 0 )        {                         // writing in the file using fputs()            fputs(dataToBeWritten, filePointer) ;            fputs("\n", filePointer) ;        }                 // Closing the file using fclose()        fclose(filePointer) ;                 printf("Data successfully written in file GfgTest.c\n");        printf("The file is now closed.") ;    }    return 0;       }
       
      Example 2: Program to Open a File, Read from it, And Close the File 
C
// C program to Open a File,// Read from it, And Close the File # include <stdio.h># include <string.h> int main( ){     // Declare the file pointer    FILE *filePointer ;         // Declare the variable for the data to be read from file    char dataToBeRead[50];     // Open the existing file GfgTest.c using fopen()    // in read mode using "r" attribute    filePointer = fopen("GfgTest.c", "r") ;         // Check if this filePointer is null    // which maybe if the file does not exist    if ( filePointer == NULL )    {        printf( "GfgTest.c file failed to open." ) ;    }    else    {                 printf("The file is now opened.\n") ;                 // Read the dataToBeRead from the file        // using fgets() method        while( fgets ( dataToBeRead, 50, filePointer ) != NULL )        {                     // Print the dataToBeRead            printf( "%s" , dataToBeRead ) ;        }                 // Closing the file using fclose()        fclose(filePointer) ;                 printf("Data successfully read from file GfgTest.c\n");        printf("The file is now closed.") ;    }    return 0;       }
       
      Example 3: Program to write to a Binary file using fwrite() 
C
#include <stdio.h>#include <stdlib.h>struct threeNum{int n1, n2, n3;};int main(){ int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","wb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n)  //Program Code Submitted by Susobhan Akhuli { num.n1 = n; num.n2 = 5*n; num.n3 = 5*n + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0;}
       
      Example 4: Program to Read from a binary file using fread() 
C
#include <stdio.h>#include <stdlib.h>struct threeNum{ int n1, n2, n3;};int main(){ int n; struct threeNum num; FILE *fptr; if ((fptr = fopen("C:\\program.bin","rb")) == NULL){ printf("Error! opening file"); // Program exits if the file pointer returns NULL. exit(1); } for(n = 1; n < 5; ++n)  //Program Code Submitted by Susobhan Akhuli { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3); } fclose(fptr);   return 0;}
      
RishabhPrabhu
RajanKumar3
istwasanders
RuturajM
shreyashagrawal
susobhanakhuli
singghakshay
gulshankumarar231
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Converting Strings to Numbers in C/C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
UDP Server-Client implementation in C