0
0
Cprogramming~5 mins

Error handling in files in C

Choose your learning style9 modes available
Introduction

We use error handling in files to check if file actions like opening or reading worked well. This helps avoid crashes and lets us fix problems smoothly.

When opening a file to read or write data.
When reading data from a file to ensure it was successful.
When writing data to a file to confirm it saved correctly.
When closing a file to check if it closed without errors.
Syntax
C
FILE *file = fopen("filename.txt", "r");
if (file == NULL) {
    // handle error
}

// Use file

if (fclose(file) != 0) {
    // handle error
}

fopen returns NULL if it fails to open the file.

Always check if the file pointer is NULL before using the file.

Examples
This checks if the file "data.txt" opens for reading. If not, it prints an error and stops the program.
C
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
    printf("Failed to open file.\n");
    return 1;
}
Uses perror to print a system error message if opening the file fails.
C
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
    perror("Error opening file");
    return 1;
}
Checks if closing the file worked. If not, it prints an error message.
C
if (fclose(file) != 0) {
    printf("Error closing the file.\n");
}
Sample Program

This program tries to open a file named "example.txt" for reading. It checks if the file opened successfully. Then it reads the first line and prints it. It also checks if reading and closing the file worked, printing messages if errors happen.

C
#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Cannot open example.txt\n");
        return 1;
    }

    char buffer[100];
    if (fgets(buffer, sizeof(buffer), file) == NULL) {
        printf("Failed to read from file or file is empty\n");
        fclose(file);
        return 1;
    }

    printf("First line: %s", buffer);

    if (fclose(file) != 0) {
        printf("Error closing the file\n");
        return 1;
    }

    return 0;
}
OutputSuccess
Important Notes

Always check the return value of fopen before using the file pointer.

Use perror to get helpful system error messages.

Remember to close files with fclose and check its return value.

Summary

Error handling helps your program avoid crashes when working with files.

Check if fopen returns NULL before reading or writing.

Always close files and check if closing worked.