home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / file / error.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-11-01  |  1.8 KB  |  59 lines

  1. /* ERROR.C illustrates stream file error handling. Functions illustrated
  2.  * include:
  3.  *      ferror          clearerr        exit            _exit
  4.  *      perror          strerror        _strerror
  5.  *
  6.  * The _exit routine is not specifically illustrated, but it is the same
  7.  * as exit except that file buffers are not flushed and atexit and onexit
  8.  * are not called.
  9.  */
  10.  
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <stdlib.h>
  14. #include <errno.h>
  15. enum BOOL { FALSE, TRUE };
  16.  
  17. FILE *stream;
  18. char string[] = "This should never be written";
  19. void errortest( FILE *stream, char *msg, int fterm );
  20.  
  21. main( int argc, char *argv[] )
  22. {
  23.     /* Open file and test to see if open caused error. If so, terminate. */
  24.     stream = fopen( argv[1], "r" );
  25.     errortest( stream, "Can't open file", TRUE );
  26.  
  27.     /* Try to write to a read-only file, then test to see if write
  28.      * caused error. If so, clear error, but don't terminate.
  29.      */
  30.     fprintf( stream, "%s\n", string );
  31.     errortest( stream, "Can't write file", FALSE );
  32.     exit( 0 );
  33. }
  34.  
  35. /* Error test routine takes a stream, a message, and a flag telling whether
  36.  * to terminate if there is an error.
  37.  */
  38. void errortest( FILE *stream, char *msg, int fterm )
  39. {
  40.     /* If stream doesn't exist (failed fopen) or if there is an error
  41.      * on the stream, handle error.
  42.      */
  43.     if( (stream == NULL) || (ferror( stream )) )
  44.     {
  45.         perror( msg );
  46.         /* _strerror and strerror can be used to get the same result
  47.          * as perror, as illustrated by these lines (commented out).
  48.         printf( "%s: %s\n", msg, strerror( errno ) );
  49.         printf( _strerror( msg ) );
  50.          */
  51.  
  52.         /* Terminate or clear error, depending on terminate flag. */
  53.         if( fterm )
  54.             exit( errno );
  55.         else
  56.             clearerr( stream );
  57.     }
  58. }
  59.