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?✗ Incorrect
fopen() returns NULL when it cannot open the file.Which function prints a descriptive error message related to the last file operation?
✗ Incorrect
perror() prints a message describing the last error.Why should you always call
fclose() after finishing file operations?✗ Incorrect
fclose() frees resources and ensures data is saved correctly.What global variable holds the error code after a failed file operation?
✗ Incorrect
errno stores the error code after a failure.If
fopen() returns NULL, what is the best next step?✗ Incorrect
You should print the error with
perror() and handle the failure properly.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.