In C language,
perror
is a library function used to display the error description associated with the previous system call. It is used to process and displayerrno
error messages from variables.
When a system call fails, such as open
, read
, write
etc., errno
it will be set to an error code indicating what error occurred. Use perror
to display a descriptive error message related to the error code to the user.
perror
The prototype is as follows:
#include <stdio.h>
void perror(const char *s);
where s
is a string usually used to describe where or why the error occurred. When perror
called, it prints the argument s
, followed by a colon, a space, and errno
an error message related to the current value.
Example:
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("non_existent_file.txt", "r");
if (fp == NULL) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
// ...其他代码...
fclose(fp);
return 0;
}
If the file "non_existent_file.txt" does not exist, the above code will output an error message similar to the following:
Error opening file: No such file or directory
Here "Error opening file" is perror
the description we provided, and "No such file or directory" is errno
the system error message associated with the value.