/* * Scenario 3: stdio Buffering * =========================== * This version uses fgetc() which is buffered by stdio. * It reads byte-by-byte in C code, but stdio buffers internally. * * Compile: gcc -O2 -o read_stdio read_stdio.c * * EXERCISES: * 1. Run: time ./read_stdio testfile * 2. Compare: strace -c ./read_stdio testfile * 3. Notice fewer syscalls than read_slow, but more than read_fast * 4. Why? Default stdio buffer is ~4KB, we use 64KB in read_fast */ #include #include int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FILE *fp = fopen(argv[1], "rb"); if (!fp) { perror("fopen"); return 1; } int c; unsigned long byte_count = 0; unsigned long checksum = 0; /* fgetc is buffered internally by stdio */ while ((c = fgetc(fp)) != EOF) { byte_count++; checksum += (unsigned char)c; } fclose(fp); printf("Read %lu bytes\n", byte_count); printf("Checksum: %lu\n", checksum); return 0; }