illustris 4fb1bd90db
init
2026-01-08 18:11:30 +05:30

53 lines
1.2 KiB
C

/*
* Scenario 3: Buffered I/O - The Fix
* ===================================
* This program reads a file in large chunks, dramatically reducing syscalls.
*
* Compile: gcc -O2 -o read_fast read_fast.c
*
* EXERCISES:
* 1. Run: time ./read_fast testfile
* 2. Compare: strace -c ./read_fast testfile
* 3. Notice the ~1000x reduction in syscalls
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFFER_SIZE 65536 /* 64KB buffer */
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
char buffer[BUFFER_SIZE];
unsigned long byte_count = 0;
unsigned long checksum = 0;
ssize_t bytes_read;
/* Read in large chunks - much better! */
while ((bytes_read = read(fd, buffer, BUFFER_SIZE)) > 0) {
for (ssize_t i = 0; i < bytes_read; i++) {
checksum += (unsigned char)buffer[i];
}
byte_count += bytes_read;
}
close(fd);
printf("Read %lu bytes\n", byte_count);
printf("Checksum: %lu\n", checksum);
return 0;
}