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

  1. /* BUFTEST.C illustrates buffer control for stream I/O using functions:
  2.  *      setbuf              setvbuf
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <time.h>
  8. #define BUF2SIZ 2048
  9.  
  10. long countln( FILE *stream );           /* Prototype        */
  11. char buf1[BUFSIZ], buf2[BUF2SIZ];       /* File buffers     */
  12.  
  13. main( int argc, char *argv[] )
  14. {
  15.     time_t start;
  16.     FILE *stream;
  17.     int  c;
  18.  
  19.     /* Use our buffer with the default size. This gives us the option
  20.      * of examining and/or modifying the buffer during I/0 (though the
  21.      * example doesn't illustrate this).
  22.      */
  23.     if( (stream = fopen( argv[1], "rt" )) == NULL )
  24.         exit( 1 );
  25.     setbuf( stream, buf1 );
  26.     start = clock();
  27.     c = countln( stream );
  28.     printf( "Time: %5.2f\tBuffering: Normal\tBuffer size: %d\n",
  29.              ((float)clock() - start) / CLK_TCK, BUFSIZ );
  30.  
  31.     /* Use a larger buffer. */
  32.     if( (stream = fopen( argv[1], "rt" )) == NULL )
  33.         exit( 1 );
  34.     setvbuf( stream, buf2, _IOFBF, sizeof( buf2 ) );
  35.     start = clock();
  36.     c = countln( stream );
  37.     printf( "Time: %5.2f\tBuffering: Normal\tBuffer size: %d\n",
  38.              ((float)clock() - start) / CLK_TCK, BUF2SIZ );
  39.  
  40.     /* Try it with no buffering. */
  41.     if( (stream = fopen( argv[1], "rt" )) == NULL )
  42.         exit( 1 );
  43.     setvbuf( stream, NULL, _IONBF, 0 );
  44.     start = clock();
  45.     c = countln( stream );
  46.     printf( "Time: %5.2f\tBuffering: Normal\tBuffer size: %d\n",
  47.              ((float)clock() - start) / CLK_TCK, 0 );
  48.  
  49.     printf( "File %s has %d lines", argv[1], c );
  50.     exit( 0 );
  51. }
  52.  
  53. /* Count lines in text files and close file. */
  54. long countln( FILE *stream )
  55. {
  56.     char linebuf[120];
  57.     long c = 0;
  58.  
  59.     while( !feof( stream ) )
  60.     {
  61.         fgets( linebuf, 121, stream );
  62.         ++c;
  63.     }
  64.     fclose( stream );
  65.     return c;
  66. }
  67.