qc.hlp (Table of Contents; Topic list)
BUFTEST.C
                                             Up Contents Index Back
────────────────────────────────────────────────────────────────────────────
 
/* BUFTEST.C illustrates buffer control for stream I/O, using function:
 *      setvbuf
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
long countln( FILE *stream );           /* Prototype        */
char buf[BUFSIZ * 4];                   /* File buffer      */
 
void main( int argc, char *argv[] )
{
    time_t start, end;
    FILE *stream;
    long c;
 
    /* Use standard buffer. */
    if( (stream = fopen( argv[1], "rt" )) == NULL )
    {
        printf( "SYNTAX: BUFTEST filename\n" );
        exit( 1 );
    }
    start = clock();
    c = countln( stream );
    end = clock();
    printf( "Time: %5.1f\tBuffering: Normal\tBuffer size: %d\n",
             ((float)end - start) / CLK_TCK, BUFSIZ );
 
    /* Use a larger buffer. */
    if( (stream = fopen( argv[1], "rt" )) == NULL )
        exit( 1 );
    setvbuf( stream, buf, _IOFBF, sizeof( buf ) );
    start = clock();
    c = countln( stream );
    end = clock();
    printf( "Time: %5.1f\tBuffering: Normal\tBuffer size: %d\n",
             ((float)end - start) / CLK_TCK, BUFSIZ * 4 );
 
    /* Try it with no buffering. */
    if( (stream = fopen( argv[1], "rt" )) == NULL )
        exit( 1 );
    setvbuf( stream, NULL, _IONBF, 0 );
    start = clock();
    c = countln( stream );
    end = clock();
    printf( "Time: %5.1f\tBuffering: None\tBuffer size: %d\n",
             ((float)end - start) / CLK_TCK, 0 );
 
    printf( "File %s has %ld lines\n", argv[1], c );
    exit( 0 );
}
 
/* Counts lines in a text file and closes file */
long countln( FILE *stream )
{
    char linebuf[256];
    long c = 0;
 
    while( !feof( stream ) )
    {
        if( fgets( linebuf, 255, stream ) == NULL )
            break;
        ++c;
    }
    fclose( stream );
    return c;
}