Reputation: 1808
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.
Upvotes: 1
Views: 3163
Reputation: 24890
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);
Upvotes: 7
Reputation: 61713
read()
returns the number of bytes read (when nothing goes wrong).
Upvotes: 1