📖 Scenario: Imagine you are writing a small program that tries to open a file. If the file does not exist or cannot be opened, you want to show a clear error message to the user.
🎯 Goal: You will create a program that attempts to open a file and uses perror and strerror functions to display error messages when the file cannot be opened.
📋 What You'll Learn
Create a variable to hold the filename
Attempt to open the file using fopen
Use perror to print an error message if opening fails
Use strerror with errno to get the error message string
Print the error message string using printf
💡 Why This Matters
🌍 Real World
When programs try to open files or perform system calls, errors can happen. Showing clear error messages helps users understand what went wrong.
💼 Career
Understanding how to handle and display system errors is important for debugging and writing reliable C programs in many software development jobs.
Progress0 / 4 steps
1
Set up the filename variable
Create a char pointer variable called filename and set it to the string "nonexistent.txt".
C
Hint
Use char *filename = "nonexistent.txt"; to store the file name.
2
Try to open the file
Add a FILE pointer variable called file and use fopen(filename, "r") to try opening the file for reading.
C
Hint
Use FILE *file = fopen(filename, "r"); to open the file.
3
Use perror to print error if file open fails
Add an if statement to check if file is NULL. Inside it, call perror("Error opening file") to print the error message.
C
Hint
Use if (file == NULL) and inside it perror("Error opening file").
4
Use strerror and printf to show error message
Inside the if block, include #include <errno.h> at the top (if not already). Then declare a char pointer err_msg and set it to strerror(errno). Finally, print the error message with printf("strerror message: %s\n", err_msg);.
C
Hint
Use char *err_msg = strerror(errno); and then printf("strerror message: %s\n", err_msg); inside the if block.
Practice
(1/5)
1. What does the perror function do in C?
easy
A. Prints a custom message followed by the system error message
B. Returns a string describing an error number
C. Terminates the program immediately
D. Clears the error state of the program
Solution
Step 1: Understand perror purpose
perror prints a message you provide, then adds the system error message related to the last error.
Step 2: Compare with other options
strerror returns a string but does not print; program termination or clearing errors are unrelated.
Final Answer:
Prints a custom message followed by the system error message -> Option A
Quick Check:
perror prints message + system error [OK]
Hint: perror prints errors; strerror returns error strings [OK]
Common Mistakes:
Confusing perror with strerror
Thinking perror returns a string
Assuming perror stops the program
2. Which of the following is the correct syntax to print an error message using perror with the text "File error"?
easy
A. perror(File_error);
B. perror(File error);
C. perror("File error");
D. perror('File error');
Solution
Step 1: Check correct string syntax in C
Strings must be in double quotes, so "File error" is correct.
Step 2: Validate perror usage
perror takes a const char* string, so perror("File error") is correct syntax.
Final Answer:
perror("File error"); -> Option C
Quick Check:
Use double quotes for strings in perror [OK]
Hint: Use double quotes for strings in perror [OK]
Common Mistakes:
Using single quotes instead of double quotes
Passing variable names without quotes
Missing parentheses in function call
3. What will be the output of the following C code snippet if errno is set to ENOENT (No such file or directory)?
strerror returns a string describing the error number stored in errno.
Step 2: Match errno value to message
ENOENT means "No such file or directory", so strerror(errno) returns that message.
Final Answer:
Error: No such file or directory -> Option D
Quick Check:
strerror(ENOENT) = "No such file or directory" [OK]
Hint: strerror(errno) shows error message for current error [OK]
Common Mistakes:
Confusing error messages for different errno values
Assuming strerror prints instead of returns string
Not including header
4. Identify the error in this code snippet that tries to print an error message:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
int errnum = ENOENT;
printf("Error: %s\n", perror(errnum));
return 0;
}
medium
A. Using perror inside printf is incorrect; perror prints directly and returns void
B. Missing header
C. Incorrect error number assigned to errnum
D. printf format specifier %s should be %d
Solution
Step 1: Check perror return type
perror prints directly to stderr and returns void; it does not return a string.
Step 2: Analyze usage inside printf
Passing perror(errnum) inside printf is invalid because perror returns void, not a string.
Final Answer:
Using perror inside printf is incorrect; perror prints directly and returns void -> Option A
Quick Check:
perror prints itself, don't use inside printf [OK]
Hint: perror prints error; don't use inside printf [OK]
Common Mistakes:
Using perror inside printf expecting a string
Confusing perror and strerror return types
Ignoring compiler warnings about void return
5. You want to write a function that opens a file and prints a clear error message if it fails. Which approach correctly uses perror and strerror together to achieve this?
FILE *open_file(const char *filename) {
FILE *f = fopen(filename, "r");
if (!f) {
// What to do here?
}
return f;
}
hard
A. Call perror(filename) without message, then return NULL
B. Call perror("Failed to open file") to print error, then return NULL
C. Print printf("Error: %s\n", strerror(errno)) only, then return NULL
D. Return NULL without printing any error message
Solution
Step 1: Understand error reporting with perror
perror prints your message plus the system error, making it clear why fopen failed.
Step 2: Compare options for clarity
Call perror("Failed to open file") to print error, then return NULL uses perror("Failed to open file"), which is clear and standard. Print printf("Error: %s\n", strerror(errno)) only, then return NULL prints only strerror message without context. Call perror(filename) without message, then return NULL prints filename only, which is less clear. Return NULL without printing any error message prints nothing.
Final Answer:
Call perror("Failed to open file") to print error, then return NULL -> Option B
Quick Check:
Use perror with custom message for clear errors [OK]
Hint: Use perror with custom text for clear error messages [OK]
Common Mistakes:
Printing strerror without context message
Using perror with filename only, confusing output
Not printing any error message on failure
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.