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

  1. /* FUNGET.C illustrates getting and ungetting characters from a file.
  2.  * Functions illustrated include:
  3.  *      getc            getchar         ungetc
  4.  *      fgetc           fgetchar
  5.  *
  6.  * Although getchar and fgetchar are not specifically used in the example,
  7.  * they are equivalent to using getc or fgetc with stdin. See HEXDUMP.C
  8.  * for another example of getc and fgetc.
  9.  */
  10.  
  11. #include <conio.h>
  12. #include <stdio.h>
  13. #include <ctype.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16.  
  17. void getword( FILE *stream, char *buf );
  18. void skiptoword( FILE *stream );
  19.  
  20. main()
  21. {
  22.     char buffer[128];
  23.     FILE *infile;
  24.  
  25.     printf( "Enter file name: " );
  26.     gets( buffer );
  27.     if( (infile = fopen( buffer, "rb" )) == NULL )
  28.     {
  29.         perror( "Can't open file" );
  30.         exit( 1 );
  31.     }
  32.  
  33.     /* Read each word and print reversed version. */
  34.     while( 1 )
  35.     {
  36.         skiptoword( infile );
  37.         getword( infile, buffer );
  38.         puts( strrev( buffer ) );
  39.     }
  40. }
  41.  
  42. /* Read one word (defined as a string of alphanumeric characters). */
  43. void getword( FILE *stream, char *p )
  44. {
  45.     int  ch;
  46.  
  47.     do
  48.     {
  49.         /* Macro version used here, but function version could be used:
  50.         ch = fgetc( stream );
  51.          */
  52.         ch = getc( stream );        /* Get characters until EOF  */
  53.         if( ch == EOF )             /*   or non-alphanumeric     */
  54.             exit( 0 );
  55.         *(p++) = (char)ch;
  56.     } while( isalnum( ch ) );
  57.     ungetc( ch, stream );           /* Put non-alphanumeric back */
  58.     *(--p) = '\0';                  /* Null-terminate            */
  59. }
  60.  
  61. /* Throw away non-digit characters. */
  62. void skiptoword( FILE *stream )
  63. {
  64.     int  ch;
  65.  
  66.     do
  67.     {
  68.         ch = getc( stream );
  69.         if( ch == EOF )
  70.             exit( 0 );
  71.     } while( !isalnum( ch ) );
  72.     ungetc( ch, stream );
  73. }
  74.