📖 Scenario: You are writing a simple C program that reads a text file and prints its content to the screen. Sometimes the file might not exist or cannot be opened. You need to handle these errors gracefully.
🎯 Goal: Build a C program that tries to open a file called data.txt, reads its content line by line, and prints each line. If the file cannot be opened, the program should print an error message.
📋 What You'll Learn
Create a FILE* pointer variable called file.
Use fopen to open data.txt in read mode.
Check if file is NULL to detect errors.
If file is NULL, print Error: Cannot open file. and exit.
If the file opens successfully, read lines using fgets and print them.
Close the file after reading.
💡 Why This Matters
🌍 Real World
Reading files safely is important in many programs that process data from files, such as configuration files, logs, or user input files.
💼 Career
Understanding file error handling is essential for software developers to write robust programs that do not crash or behave unexpectedly when files are missing or inaccessible.
Progress0 / 4 steps
1
Create a FILE* pointer called file and open data.txt in read mode
Write code to create a FILE* pointer named file and open the file "data.txt" in read mode using fopen.
C
Hint
Use FILE *file = fopen("data.txt", "r"); to open the file.
2
Check if file is NULL and print an error message if it is
Add an if statement to check if file is NULL. If it is, print Error: Cannot open file. using printf and return 1 to exit the program.
C
Hint
Use if (file == NULL) to check for errors and printf to show the message.
3
Read lines from the file using fgets and print them
Declare a character array line with size 100. Use a while loop with fgets(line, 100, file) to read each line from the file. Inside the loop, print each line using printf.
C
Hint
Use while (fgets(line, 100, file) != NULL) to read lines and printf("%s", line) to print.
4
Close the file and finish the program
After the while loop, close the file using fclose(file). Then return 0 to end the program.
C
Hint
Use fclose(file); to close the file.
Practice
(1/5)
1. What does fopen return if it fails to open a file in C?
easy
A. 0
B. An empty string
C. -1
D. NULL
Solution
Step 1: Understand fopen behavior
The fopen function returns a pointer to a FILE object if successful.
Step 2: Identify failure return value
If fopen fails (e.g., file not found), it returns NULL to indicate error.
Final Answer:
NULL -> Option D
Quick Check:
fopen failure returns NULL [OK]
Hint: Remember: fopen returns NULL on failure, not zero or -1 [OK]
Common Mistakes:
Thinking fopen returns 0 on failure
Confusing NULL with empty string
Assuming fopen throws an error instead of returning NULL
2. Which of the following is the correct way to check if a file was opened successfully in C?
easy
A. if (file != NULL)
B. if (file == 0)
C. if (file == -1)
D. if (file == NULL)
Solution
Step 1: Recall fopen return value on failure
fopen returns NULL if it fails to open a file.
Step 2: Write correct check for success
To check if opened successfully, compare the file pointer using file != NULL.
Final Answer:
if (file != NULL) -> Option A
Quick Check:
Check file pointer against NULL for success [OK]
Hint: Check if file pointer != NULL to confirm open success [OK]
Common Mistakes:
Using 0 or -1 instead of NULL for pointer check
Checking if file == NULL to confirm success
Confusing integer and pointer comparisons
3. What will be the output of this C code snippet?
#include <stdio.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
printf("File open failed\n");
} else {
printf("File opened\n");
fclose(fp);
}
return 0;
}
medium
A. File opened
B. File open failed
C. Compilation error
D. No output
Solution
Step 1: fopen tries to open a non-existing file
The file "nonexistent.txt" does not exist, so fopen returns NULL.
Step 2: Check the if condition and output
Since fp == NULL is true, the program prints "File open failed".
Final Answer:
File open failed -> Option B
Quick Check:
fopen fails, prints failure message [OK]
Hint: If fopen returns NULL, print error message [OK]
Common Mistakes:
Assuming file opens successfully
Ignoring the NULL check
Expecting compilation error due to fopen
4. Identify the error in this code snippet that opens and closes a file: