Reading the man pages and some code did not really help me in
understanding the difference between – or better, when I should use – perror("...") or fprintf(stderr, "...").
Reading the man pages and some code did not really help me in understanding
Share
Calling
perrorwill give you the interpreted value oferrno, which is a thread-local error value written to by POSIX syscalls (i.e., every thread has it’s own value forerrno). For instance, if you made a call toopen(), and there was an error generated (i.e., it returned-1), you could then callperrorimmediately afterwards to see what the actual error was. Keep in mind that if you call other syscalls in the meantime, then the value inerrnowill be written over, and callingperrorwon’t be of any use in diagnosing your issue if an error was generated by an earlier syscall.fprintf(stderr, ...)on the other-hand can be used to print your own custom error messages. By printing tostderr, you avoid your error reporting output being mixed with “normal” output that should be going tostdout.Keep in mind that
fprintf(stderr, "%s\n", strerror(errno))is similar toperror(NULL)since a call tostrerror(errno)will generate the printed string value forerrno, and you can then combined that with any other custom error message viafprintf.