jorge saraiva jorge saraiva - 4 months ago 30
C Question

What's difference between perror and fprintf to stderr?

I know both can work as error messages,

perror(" ");
fprintf(stderr, " ");

but what are really differences between them? What are advantages/disadvantages of each ?


Per the perror() standard:

The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message, which shall be written to the standard error stream as follows:

  • First (if s is not a null pointer and the character pointed to by s is not the null byte), the string pointed to by s followed by a <colon> and a <space>.

  • Then an error message string followed by a <newline>.

The contents of the error message strings shall be the same as those returned by strerror() with argument errno.


perror( " " );

will emit something like

 : invalid argument

to stderr, depending on the current value of errno.


fprintf( stderr, " " );

will emit only a space character to stderr and not print the string representation of the current errno value.

fprintf( stderr, " " ); in isolation is pretty useless. perror( " " ); will provide data about the current value of errno.