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
[[email protected] ch15_Input_Output_Functions]# ./a.out File Argument Missing [[email protected] 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.
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Computer Science MCQs
- Buy Computer Science Books
- Apply for C Internship
- Apply for Computer Science Internship
- Practice BCA MCQs