Answer: Generally, we write programs to perform specific operations, for ex. opening a file for reading. Such operations are accomplished by using standard library functions. These functions in turn request O.S. to perform the requested operation. Then there’s chance that O.S. might fail for ex. attempting to open a requested file for reading that doesn’t exit. In such situations, O.S. rather to show up an error massage indicates something went wrong. This error information library
functions then pass to user program after saving an error code in the external integer variable errno (defined in errno.h) to indicate exactly why the operation failed.
perror() simplifies reporting of such specific errors to user. It’s prototype is as follows
void perror(char const *message);
Note that if message isn’t NULL and points to a non-empty string, then message is printed and is followed by a colon and a space. Message explaining the error code currently in errno is then printed. For ex., we see a simple C program below
/* perror.c -- simplifies error reporting in unifying way */ #include <stdio.h> #include <error.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp; if (argc == 1) { puts("File Argument Missing"); exit(EXIT_FAILURE); } fp = fopen(argv[1], "r"); if (fp == NULL) { perror("File Open"); exit(EXIT_FAILURE); } return 0; }
Output is as follows
[root@localhost ch15_Input_Output_Functions]# ./a.out File Argument Missing [root@localhost ch15_Input_Output_Functions]# ./a.out bye.text File Open: No such file or directory
Note that above program attempts to open a file for reading whose name is given on command line. If file doesn’t exist, perror() indicates this by displaying “No such file or directory after the colon”.
Also, notice that external integer variable errno modifies when error occurs otherwise it’s not. This means that we can’t test errno to determine whether or not some error occurred.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Apply for Computer Science Internship
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Practice Computer Science MCQs