Search code examples
cstderr

perror() or own string output to stderr in C


Is there a preferable way to report errors in C? For example if a file that is supposed to be opened does not exist, should I use

if( fp == NULL ) 
{
      perror("Error: ");
      return(-1);
}

(copied from http://www.tutorialspoint.com/c_standard_library/c_function_perror.htm )

or

if( fp == NULL ) 
{
      fprintf(stderr, "Unable to open file for reading.\n");
      return(-1);
}

Solution

  • You can use perror() or strerror to get the error message. If you want to postpone the display of error message or if you want to log the message to a file, then save the errno and use strerror() because perror only writes to the standard error stream and it uses the global errno set and the errno might change any time if any library function is called before printing the error message.

    Example using saved errno:

    int savederrno;
    ....
    if( fp == NULL ) 
    {
      savederrno = errno; /* Save the errno immediately after an api/lib function or a system call */
      /*If you want to write to a log file now, write here using strerror and other library calls */
    }
    
    ....
    /* use strerror function to get the error message and write to log
        or write to std error etc*/
    

    The following man pages explain the error reporting in detail.

    http://www.gnu.org/software/libc/manual/html_node/Error-Messages.html http://man7.org/linux/man-pages/man3/errno.3.html