Section 16.15. Error Messages


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

Purpose

Function

Header

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

perror( )

stdio.h

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

strerror( )

string.h


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 



C(c) In a Nutshell
C in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596006977
EAN: 2147483647
Year: 2006
Pages: 473

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net