Skip to main content

Errno Perror and Strerror

In C programming, errno, perror(), and strerror() are all related to handling and reporting errors that occur during program execution.

errno

  • The C standard library provides the errno variable, which is typically an external global variable, to store error codes for library functions.

  • The value of errno is typically defined in the <errno.h> header file. You can use errno to determine the specific error that occurred after a function call.

  • When a function encounters an error, it sets the appropriate error code in errno to indicate the nature of the error.

  • The calling code can check the value of errno to determine if an error occurred and use functions like perror() or strerror() to obtain error descriptions.

perror()

  • perror() is a function that prints a user-friendly error message corresponding to the current value of errno.

  • It takes a string argument (typically a custom error message) and appends the error message corresponding to errno.

  • The resulting message is printed to the standard error stream (stderr).

The syntax for perror() is:

void perror(const char *str);

Example

#include <stdio.h>
#include <errno.h>

int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("Error");
}
return 0;
}

Explanation:

  • If the file "nonexistent.txt" does not exist, the fopen() function will fail and set errno to indicate the specific error.
  • The perror() function will then print a message like "Error: No such file or directory" to the standard error stream.

strerror()

  • strerror() is a function that returns a string representation of the error code passed to it.

  • It takes an error code (typically from errno) as an argument and returns a pointer to a string containing a description of the error.

The syntax for strerror() is:

char *strerror(int errnum);

Example

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
printf("Error: %s\n", strerror(errno));
}
return 0;
}

Explanation

  • strerror(errno) is used to obtain the error message corresponding to the current value of errno, and it is then printed using printf(). This will produce the same output as the perror() example.
perror() and strerror()

Both perror() and strerror() are helpful in providing descriptive error messages when dealing with system calls or library functions that can fail. They make error handling and debugging easier by providing useful information about the encountered errors.