C File Handling

In C, file handling allows you to create, open, read, write, and close files. C provides a set of functions to interact with files, making it easier to manage data stored in files. File handling is essential for programs that need to store large amounts of data or work with data that persists between program executions.

Opening a File

To perform any file operations, a file must first be opened using the fopen() function. This function takes two arguments: the file name and the mode in which the file is opened.

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

The mode argument can be one of the following:

Example: Opening and Writing to a File

                        
#include <stdio.h>
        
int main() 
{
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Unable to open file.\n");
        return 1;
    }
        
    fprintf(file, "Hello, File Handling in C!\n");
        
    fclose(file);
    return 0;
}
                        
                    

Output:

(No direct output to console, but the text will be written to example.txt.)

Reading from a File

After opening a file, data can be read using functions like fscanf() or fgets(). Here’s an example of reading from a file:

                        
#include <stdio.h>
        
int main() 
{
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Unable to open file.\n");
        return 1;
    }          
        
    char buffer[255];
    fgets(buffer, sizeof(buffer), file);

    printf("File content: %s", buffer);

    fclose(file);       
    return 0;
}
                        
                    

Output:

File content: Hello, File Handling in C!

Closing a File

Once the file operation is completed, the file should be closed using the fclose() function to free system resources.

                        
int fclose(FILE *file);
                        
                    

Error Handling

C provides functions like feof() to check for end-of-file and ferror() to check for errors during file operations.

                        
#include <stdio.h>
        
int main() 
{
    FILE *file = fopen("non_existent_file.txt", "r");
    if (file == NULL) {
        printf("Error opening file: %s\n", strerror(errno));
    }           
        
    return 0;
}
                        
                    

Output:

Error opening file: No such file or directory

Key Functions

Key Points