7.3) Error handling and file I/O operations in C

Error Handling in File I/O

Error handling is the practice of dealing with unexpected situations that might occur during file I/O operations. This ensures your program can gracefully handle issues like missing files or permission problems.

1. Checking for File Opening Errors

When opening a file, you should always check if the file was successfully opened before performing operations on it.

Example: Checking for File Opening Errors

#include <stdio.h>

int main() {
    FILE *filePointer;

    filePointer = fopen("nonexistent.txt", "r");

    if (filePointer == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    // Perform operations on the file

    fclose(filePointer);

    return 0;
}

Output:

File cannot be opened.

In this example, the file “nonexistent.txt” doesn’t exist, so fopen returns NULL, indicating an error.

2. Error Codes

File I/O functions often return special values or set global variables like errno to indicate errors. You can use these values to determine the type of error that occurred.

Example: Using errno to Display Error Message

#include <stdio.h>
#include <errno.h>

int main() {
    FILE *filePointer;

    filePointer = fopen("nonexistent.txt", "r");

    if (filePointer == NULL) {
        printf("File cannot be opened. Error code: %d\n", errno);
        perror("Error message");
        return 1;
    }

    fclose(filePointer);

    return 0;
}

Output:

File cannot be opened. Error code: 2
Error message: No such file or directory

File I/O Operations

File I/O operations involve reading from and writing to files. Basic functions include fprintf, fscanf, fputc, and fgetc.

Example: Writing and Reading from a File

#include <stdio.h>

int main() {
    FILE *filePointer;
    int num = 42;

    filePointer = fopen("data.txt", "w");

    if (filePointer == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    fprintf(filePointer, "The number is: %d\n", num);
    fclose(filePointer);

    // Reading from the file
    filePointer = fopen("data.txt", "r");

    if (filePointer == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    int readNum;
    fscanf(filePointer, "The number is: %d", &readNum);
    printf("Read number: %d\n", readNum);

    fclose(filePointer);

    return 0;
}

Output:

Read number: 42

In this example, the program writes a number to a file and then reads it back from the file.

Understanding error handling is crucial to ensure your program behaves correctly, even in unexpected situations. Proper error handling helps prevent crashes and makes your program more robust.