Previous Page
Next Page

16.15. Error Messages

Various standard library functions set the global variable errno to a value indicating the type of error encountered during execution (see the section on errno.h in Chapter 15). The functions in Table 16-28 generate an appropriate error message for the current the value of errno.

Table 16-28. Error message functions




Print an appropriate error message on stderr for the current value of errno

perror( )


Return a pointer to the appropriate error message for a given error number

strerror( )


The function perror( ) prints the string passed to it as an argument, followed by a colon and the error message that corresponds to the value of errno. This error message is the one that strerror( ) would return if called with the same value of errno as its argument. Here is an example:

    if ( remove("test1") != 0)  // If we can't delete the file ...
      perror( "Couldn't delete 'test1'" );

This perror( ) call produces the same output as the following statement:

    fprintf( stderr, "Couldn't delete 'test1': %s\n", strerror( errno ) );

In this example, if the file test1 does not exist, a program compiled with GCC prints the following message:

    Couldn't delete 'test1': No such file or directory

Previous Page
Next Page