File Handling in C

By Paribesh Sapkota

File Handling in C

File handling in C involves the creation, reading, writing, and manipulation of files stored on a disk. This allows data to persist between program executions and facilitates the exchange of data between programs.

Concept of File

A file is a collection of data stored on a disk or other storage medium. Files can be used to store a wide variety of data types, including text, images, and binary data. In C, file operations are handled using the standard I/O library functions provided in stdio.h.

Types of Files

Text Files

  • Text Files: Contain readable characters and are often used to store plain text. Each line of text ends with a newline character (\n).

Binary Files

  • Binary Files: Contain data in a binary format, which is not human-readable. These files store data in the same format as it is stored in memory, which can include text, images, and other types of data.

Functions for file handling

There are many functions in the C library to open, read, write, search and close the file. A list of file functions are given below:

No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()

We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below.

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

The fopen() function accepts two parameters:

  • The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like “c://some_folder/some_file.ext”.
  • The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode

Consider the following example which opens a file in write mode.

#include<stdio.h>  
void main( )  
{  
FILE *fp ;  
char ch ;  
fp = fopen("file_handle.c","r") ;  
while ( 1 )  
{  
ch = fgetc ( fp ) ;  
if ( ch == EOF )  
break ;  
printf("%c",ch) ;  
}  
fclose (fp ) ;  
}

Closing File: fclose()

The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below:

int fclose( FILE *fp );

// 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;
}

Input Output Operations in File

nput and output operations in files are crucial for handling data storage and retrieval in C programs. These operations allow programs to read data from and write data to files on the disk. Let’s delve into these operations for both text and binary files.

Text File Operations

Writing to a Text File

  1. Using fprintf: Similar to printf, but writes formatted data to a file.
    #include <stdio.h>
    
    int main() {
        FILE *filePtr = fopen("example.txt", "w"); // Open file for writing
        if (filePtr != NULL) {
            fprintf(filePtr, "Hello, World!\n"); // Write formatted text
            fprintf(filePtr, "This is a text file.\n");
            fclose(filePtr); // Close the file
        } else {
            printf("Failed to open the file for writing.\n");
        }
        return 0;
    }
    

    Using fputs: Writes a string to a file

    #include <stdio.h>
    
    int main() {
        FILE *filePtr = fopen("example.txt", "w"); // Open file for writing
        if (filePtr != NULL) {
            fputs("Hello, World!\n", filePtr); // Write a string
            fputs("This is a text file.\n", filePtr);
            fclose(filePtr); // Close the file
        } else {
            printf("Failed to open the file for writing.\n");
        }
        return 0;
    }
    

    Reading from a Text File

    1. Using fscanf: Similar to scanf, but reads formatted input from a file.
    #include <stdio.h>
    
    int main() {
        FILE *filePtr = fopen("example.txt", "r"); // Open file for reading
        if (filePtr != NULL) {
            char str[100];
            while (fscanf(filePtr, "%99s", str) != EOF) { // Read formatted text
                printf("%s ", str);
            }
            fclose(filePtr); // Close the file
        } else {
            printf("Failed to open the file for reading.\n");
        }
        return 0;
    }
    
    1. Using fgets: Reads a line from a file.
      #include <stdio.h>
      
      int main() {
          FILE *filePtr = fopen("example.txt", "r"); // Open file for reading
          if (filePtr != NULL) {
              char buffer[100];
              while (fgets(buffer, 100, filePtr) != NULL) { // Read a line
                  printf("%s", buffer);
              }
              fclose(filePtr); // Close the file
          } else {
              printf("Failed to open the file for reading.\n");
          }
          return 0;
      }
      

      Binary File Operations

      Writing to a Binary File

      1. Using fwrite: Writes binary data to a file.
    #include <stdio.h>
    
    int main() {
        FILE *filePtr = fopen("example.bin", "wb"); // Open file for writing in binary mode
        if (filePtr != NULL) {
            int data = 123;
            fwrite(&data, sizeof(data), 1, filePtr); // Write binary data
            fclose(filePtr); // Close the file
        } else {
            printf("Failed to open the file for writing.\n");
        }
        return 0;
    }
    

    Reading from a Binary File

    1. Using fread: Reads binary data from a file
      #include <stdio.h>
      
      int main() {
          FILE *filePtr = fopen("example.bin", "rb"); // Open file for reading in binary mode
          if (filePtr != NULL) {
              int data;
              fread(&data, sizeof(data), 1, filePtr); // Read binary data
              printf("Data: %d\n", data);
              fclose(filePtr); // Close the file
          } else {
              printf("Failed to open the file for reading.\n");
          }
          return 0;
      }
      

    Random Access in Files

    Random access in files allows you to move to any part of a file for reading or writing, rather than processing it sequentially from the beginning to the end. This capability is particularly useful for modifying specific parts of a file without having to read through the entire file. In C, random access is achieved using the functions fseek, ftell, and rewind.

    Functions for Random Access

    1. fseek: Moves the file pointer to a specified location.
    int fseek(FILE *stream, long offset, int origin);
    
    • stream: Pointer to the file.
    • offset: Number of bytes to offset from origin.
    • origin: Position from where offset is added. It can be:
      • SEEK_SET: Beginning of the file.
      • SEEK_CUR: Current position of the file pointer.
      • SEEK_END: End of the file.

    ftell: Returns the current position of the file pointer.

    long ftell(FILE *stream);
    
      • stream: Pointer to the file.
    1. rewind: Sets the file pointer to the beginning of the file.
    void rewind(FILE *stream);
    

    Example: Random Access in a Text File

    #include <stdio.h>
    
    int main() {
        FILE *filePtr = fopen("example.txt", "w+"); // Open file for reading and writing
        if (filePtr != NULL) {
            // Write data to the file
            fputs("Hello, World!\nThis is a text file.\n", filePtr);
    
            // Move the file pointer to the beginning
            rewind(filePtr);
    
            // Read and print the first line
            char buffer[100];
            fgets(buffer, 100, filePtr);
            printf("%s", buffer);
    
            // Move the file pointer to the 14th byte (right after "Hello, World!\n")
            fseek(filePtr, 13, SEEK_SET);
    
            // Write additional data
            fputs("INSERTED_TEXT\n", filePtr);
    
            // Move the file pointer to the beginning
            rewind(filePtr);
    
            // Read and print the modified content
            while (fgets(buffer, 100, filePtr) != NULL) {
                printf("%s", buffer);
            }
    
            // Close the file
            fclose(filePtr);
        } else {
            printf("Failed to open the file.\n");
        }
        return 0;
    }
    

    Random Access in a Binary File

    #include <stdio.h>
    
    int main() {
        FILE *filePtr = fopen("example.bin", "wb+"); // Open file for reading and writing in binary mode
        if (filePtr != NULL) {
            int data[3] = {1, 2, 3};
            fwrite(data, sizeof(int), 3, filePtr); // Write an array of integers
            
            // Move the file pointer to the second integer
            fseek(filePtr, sizeof(int), SEEK_SET);
    
            int newData = 99;
            fwrite(&newData, sizeof(int), 1, filePtr); // Overwrite the second integer
    
            // Move the file pointer back to the beginning
            rewind(filePtr);
    
            fread(data, sizeof(int), 3, filePtr); // Read the modified array
            for (int i = 0; i < 3; i++) {
                printf("data[%d] = %d\n", i, data[i]);
            }
    
            // Close the file
            fclose(filePtr);
        } else {
            printf("Failed to open the file.\n");
        }
        return 0;
    }
    

     

Important Questions
Comments
Discussion
0 Comments
  Loading . . .