When reading from a pipe in Linux (C, fread/similar), when EOF is reached, how can it be known how many bytes were read? If I read blocks at a time, fread() only returns the number of full blocks read in, and I can't read one byte at a time because that is too slow. Of course, ftell() returns -1.
+5
A:
You can do this with fread()
by setting the size
param to 1 and set the nmembers
to whatever size you like. Then the number of "members" is the number of bytes and you can still have a decent sized buffer:
char buf[8192];
size_t n;
n = fread(buf, 1, sizeof buf, f);
instead of
char buf[8192];
size_t n;
n = fread(buf, sizeof buf, 1, f);
dwc
2009-05-13 21:19:06
Will it read that much all at once (fast), or read one at a time (slow)? I would think "one at a time" is why it has both size and count arguments, not just a size argument.
c4757p
2009-05-13 21:21:00
Lucky for us, it will read as much as possible, up to `size * nmembers` bytes.
dwc
2009-05-13 21:24:02
@c4757p, The size and count are there to encourage clearly expressing a read of n elements of an array. They have no effect (other than their total) on the underlying read() calls.
RBerteig
2009-05-13 21:33:14
+1
A:
read()
returns the number of bytes read (when nothing goes wrong).
Bastien Léonard
2009-05-13 21:24:18