You're totally misunderstanding the standard I/O function. Even fgetc
is buffered. Test the issuance of actual read
calls with strace
. On my computer, reading /proc/1/maps
:
read(3, "5634f9cf6000-5634f9e44000 r-xp 0"..., 1024) = 1024
read(3, " /lib/x86_64-l"..., 1024) = 1024
read(3, " /lib/x86_64-linux-g"..., 1024) = 1024
read(3, " /lib/x86_64-l"..., 1024) = 1024
read(3, ".0.0\n7feb2b2dc000-7feb2b4db000 -"..., 1024) = 1024
read(3, "0-7feb2b8e7000 r--p 00002000 fd:"..., 1024) = 1024
read(3, "00 rw-p 0001a000 fd:00 145004 "..., 1024) = 1024
read(3, "ux-gnu/liblzma.so.5.2.2\n7feb2c1b"..., 1024) = 1024
read(3, "6_64-linux-gnu/libgcrypt.so.20.2"..., 1024) = 1024
read(3, "000 fd:00 135558 "..., 1024) = 1024
read(3, "--p 0000e000 fd:00 136910 "..., 1024) = 1024
read(3, "001e000 fd:00 131385 "..., 1024) = 1024
read(3, "1.1.0\n7feb2da14000-7feb2da15000 "..., 1024) = 1024
read(3, "0 rw-p 00000000 00:00 0 \n7feb2de"..., 1024) = 1024
read(3, "-237.so\n7feb2e492000-7feb2e69100"..., 1024) = 1024
read(3, " \n7feb2ed15000-7feb2ed36000 rw-p"..., 1024) = 637
read(3, "", 1024) = 0
The read
calls attempt to read 1024
bytes, not just one.
The program is
#include <stdio.h>
int main(void) {
FILE *f = fopen("/proc/1/maps", "r");
while (1) {
char buf[2048];
if (! fgets(buf, 2048, f)) {
break;
}
}
}
Should 1024 bytes not be enough for you, you can change the size of the underlying buffer with setvbuf(3)!