In C programming language, errors can occur during program execution, such as when a file cannot be opened or when memory cannot be allocated. It is important to handle errors properly in order to prevent the program from crashing or producing incorrect results. One way to handle errors in C is by using error handling functions such as perror() and strerror().
The perror() function is used to print a system error message to the standard error stream (stderr) along with a custom error message. The perror() function takes a single argument, which is a string that represents the custom error message.
#include <stdio.h>
#include <errno.h>
int main() {
FILE *fp = fopen("nonexistent_file.txt", "r");
if (fp == NULL) {
perror("Error opening file");
}
return 0;
}
In this example, the fopen() function is used to open a file named "nonexistent_file.txt" for reading, but since the file does not exist, the function returns NULL. The perror() function is then called with the custom error message "Error opening file", which prints a system error message to the standard error stream, such as "No such file or directory".
The strerror() function is used to convert a system error code into a string that represents the error message. The strerror() function takes a single argument, which is an integer that represents the system error code.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *fp = fopen("nonexistent_file.txt", "r");
if (fp == NULL) {
printf("Error opening file: %sn", strerror(errno));
}
return 0;
}
In this example, the fopen() function is used to open a file named "nonexistent_file.txt" for reading, but since the file does not exist, the function returns NULL. The strerror() function is then called with the errno global variable, which represents the system error code. The strerror() function converts the error code into a string that represents the error message, which is then printed to the standard output stream.
In summary, error handling functions such as perror() and strerror() are used to handle errors in C programming language. The perror() function is used to print a system error message along with a custom error message, while the strerror() function is used to convert a system error code into a string that represents the error message. By using these functions, programmers can handle errors properly and prevent their programs from crashing or producing incorrect results.