0
0
Cprogramming~5 mins

perror and strerror functions - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the perror function do in C?

perror prints a descriptive error message to stderr based on the current value of errno. It helps you understand what went wrong in your program.

Click to reveal answer
beginner
How does strerror differ from perror?

strerror returns a pointer to a string describing the error code passed to it, instead of printing it. You can use this string in your own messages or logs.

Click to reveal answer
beginner
What header file must you include to use perror and strerror?

You must include <stdio.h> for perror and <string.h> for strerror. Also, <errno.h> is needed to access errno.

Click to reveal answer
beginner
What is errno in C?

errno is a global variable set by system calls and some library functions when an error occurs. It holds an error code that perror and strerror use to show error messages.

Click to reveal answer
beginner
Show a simple example of using perror after a failed file open.
FILE *f = fopen("nofile.txt", "r");
if (!f) {
    perror("Error opening file");
}

This prints something like: Error opening file: No such file or directory

Click to reveal answer
Which header file is required to use perror in C?
A<string.h>
B<stdio.h>
C<errno.h>
D<stdlib.h>
What does strerror(errno) return?
AA string describing the last error
BAn integer error code
CPrints error to stderr
DSets errno to zero
What is the main difference between perror and strerror?
A<code>perror</code> returns error string; <code>strerror</code> prints error
BBoth print error messages
C<code>perror</code> prints error; <code>strerror</code> returns error string
DBoth return error codes
If fopen fails, which variable holds the error code?
ANULL
Bperror
Cstrerror
Derrno
Which function would you use to get a custom error message string for logging?
Astrerror
Bperror
Cprintf
Dscanf
Explain how perror and strerror help in error handling in C.
Think about how you find out what went wrong in your program.
You got /4 concepts.
    Write a short code snippet that opens a file and uses perror if the file cannot be opened.
    Remember to include <stdio.h> and check the file pointer.
    You got /3 concepts.