jorge saraiva jorge saraiva - 22 days ago 7
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 ?

Answer

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.

So,

perror( " " );

will emit something like

 : invalid argument

to stderr, depending on the current value of errno.

But

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.