C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

ERROR HANDLING IN FILE

Error handling when working with files in C is crucial to ensure the robustness and reliability of your program.

Check File Opening: Always check whether the file has been successfully opened before proceeding with read or write operations.

FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
    perror("Error opening file");
}

Check File Closure: After finishing operations on a file, always ensure that you close it properly. This step is essential to release system resources and avoid memory leaks.

if (fclose(fp) != 0) {
    perror("Error closing file");
}

Check for Errors During File Operations: Whenever you perform read or write operations on a file, check for errors and handle them accordingly. This is particularly important when using functions like fread(), fwrite(), fscanf(), fprintf(), etc.

if (fread(buffer, sizeof(char), BUFFER_SIZE, fp) != BUFFER_SIZE) {
    if (feof(fp)) {
        // End of file reached
    } else if (ferror(fp)) {
        // Error occurred during read operation
        perror("Error reading file");
        return -1; // or handle the error appropriately
    }
}

Handle File-Related Errors Appropriately: Depending on the nature of the error, you may want to take different actions. For example, if a file does not exist, you might create it or prompt the user to provide a valid file name.

Graceful Exit: When an error occurs that prevents the program from continuing, it's essential to exit gracefully. Close files and free resources before exiting.

fclose(fp);
// Other cleanup code
exit(EXIT_FAILURE);

​​​​​​​EXIT_FAILURE indicates an abnormal termination of the program due to an error.