0
0
Cprogramming~5 mins

Error handling in files in C - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of error handling when working with files in C?
Error handling helps detect and respond to problems like missing files, permission issues, or read/write errors to prevent program crashes and data loss.
Click to reveal answer
beginner
Which function is commonly used to open a file and how do you check if it failed?
The fopen() function opens a file. If it returns NULL, it means the file could not be opened, indicating an error.
Click to reveal answer
intermediate
How can you get more information about the error after a file operation fails?
You can use the global variable errno and functions like perror() or strerror() to get a human-readable error message.
Click to reveal answer
beginner
What should you always do after finishing file operations?
Always close the file using fclose() to free resources and avoid data corruption.
Click to reveal answer
beginner
Show a simple C code snippet that opens a file for reading and handles the error if the file does not exist.
#include int main() { FILE *file = fopen("data.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } // File operations here fclose(file); return 0; }
Click to reveal answer
What does fopen() return if it fails to open a file?
ANULL
B0
C-1
DA file pointer
Which function prints a descriptive error message related to the last file operation?
Aprintf()
Bperror()
Cfclose()
Dfopen()
Why should you always call fclose() after finishing file operations?
ATo open the file again
BTo check for errors
CTo delete the file
DTo free resources and save data properly
What global variable holds the error code after a failed file operation?
Aerrno
Berror_code
Cfile_error
Dstatus
If fopen() returns NULL, what is the best next step?
AIgnore and continue
BCall <code>fclose()</code>
CUse <code>perror()</code> to print the error and handle it
DTry to write to the file
Explain how to safely open a file in C and handle the case when the file cannot be opened.
Think about checking the return value of fopen and printing an error message.
You got /4 concepts.
    Describe why closing a file with fclose is important after file operations.
    Consider what happens if you don't close a file properly.
    You got /4 concepts.