/* * This program demonstrates how setvbuf can specify the kind * of buffering used for a file stream. * * Side-Effects: Output is written to a file "setvbuf.out" * (previous contents erased) * * Commands used: fflush, sprintf, fprintf, fopen, fclose, setvbuf, putc */ #include #include /* system() needs this */ #include /* toupper() needs this */ #define MAX_LINE 80 main() { char aString [MAX_LINE]; int length = 0; FILE *fp1 = NULL; FILE *fp2 = NULL; int i; sprintf(aString, "abcdefghijklmnopqrstuvwxyz\n"); length = strlen(aString); /* * remove any setvbuf.out files lingering around from previous * executions (see p. 221) */ system("rm -f setvbuf.out"); if ( (fp1 = fopen("setvbuf.out", "a+")) == NULL ) { fprintf(stderr, "Error. Couldn't open fp1 file with a+\n"); exit(1); } if ( (fp2 = fopen("setvbuf.out", "a+")) == NULL ) { fprintf(stderr, "Error. Couldn't open fp2 file with a+\n"); exit(1); } /* * First test: * set fp1 to be line buffered * set fp2 to be unbuffered */ setvbuf(fp1, NULL, _IOLBF, NULL); setvbuf(fp2, NULL, _IONBF, NULL); fprintf(fp1, "Test #1. Lowercase is line buffered, uppercase is unbuffered:\n"); fprintf(fp1, "--------------------------------------------------------------\n\n"); fflush(fp1); for (i = 0; i < length; i++) { putc (aString[i], fp1); putc (toupper(aString[i]), fp2); } fclose(fp1); fclose(fp2); /* * Re-opening files so that the setvbuf gets executed before any operation * is performed on the stream */ if ( (fp1 = fopen("setvbuf.out", "a+")) == NULL ) { fprintf(stderr, "Error. Couldn't RE-open fp1 file with a+\n"); exit(1); } if ( (fp2 = fopen("setvbuf.out", "a+")) == NULL ) { fprintf(stderr, "Error. Couldn't RE-open fp2 file with a+\n"); exit(1); } /* * Second test: * set fp1 to be unbuffered * set fp2 to be unbuffered */ setvbuf(fp1, NULL, _IONBF, NULL); setvbuf(fp2, NULL, _IONBF, NULL); fprintf(fp1, "\nTest #2. Both upper and lower case are unbuffered:\n"); fprintf(fp1, "--------------------------------------------------------------\n\n"); fflush(fp1); for (i = 0; i < length; i++) { putc (aString[i], fp1); putc (toupper(aString[i]), fp2); } }