When should you use perror ("...") and fprintf (stderr, "...")?

Reading the manual pages and some code didn't really help me understanding the difference between - or better, when I should use - perror("...") or fprintf(stderr, "...") .

+75
c stderr
Aug 24 2018-12-12T00:
source share
5 answers

Calling perror will give you the interpreted value of errno , which is the local local error value recorded using POSIX system calls (i.e., each thread has its own value for errno ). For example, if you made an open() call, and a generated error occurred (i.e., it returned -1 ), you can immediately call perror to find out what the actual error is. Keep in mind that if you make other system calls during this time, then the value will be written to errno more, and the perror call perror not be useful in diagnosing your problem if the error was generated by an earlier syscall.

fprintf(stderr, ...) on the other hand, can be used to print your own error messages. When printing to stderr you avoid displaying error messages mixed with the "normal" output, which should go to stdout .

Keep in mind that fprintf(stderr, "%s\n", strerror(errno)) is similar to perror(NULL) , since calling strerror(errno) generates a printed string value for errno , and you can combine it with any other custom error message via fprintf .

+83
Aug 24 2018-12-12T00:
source share

They do very different things.

You use perror() to print a stderr message that matches errno . You use fprintf() to print the whole stderr or any other stream. perror() is a very specialized print function:

 perror(str); 

equivalently

 if (str) fprintf(stderr, "%s: %s\n", str, strerror(errno)); else fprintf(stderr, "%s\n", strerror(errno)); 
+29
Aug 24 2018-12-12T00:
source share

perror(const char *s) : prints the line you pass, and then the line that describes the current errno value.

stderr : this is the output stream used to send your own error messages (the terminal is used by default).

Relevant

char *strerror(int errnum) : specify the error number and will return the associated error string.

+7
Aug 24 2018-12-12T00:
source share

perror () always writes to stderr; strerr (), used with fprintf (), can write to any output - including stderr, but not exclusively.

 fprintf(stdout, "Error: %s", strerror(errno)); fprintf(stderr, "Error: %s", strerror(errno)); // which is equivalent to perror("Error") 

In addition, perror overlays its own text, forming "text: error description"

0
Mar 19 '17 at 14:28
source share

The Perror function takes longer to complete the execution call; it moves from user space to kernel space, where fprintf calls go to api to kernal

-one
Feb 04 '15 at 7:53
source share



All Articles