Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

read() returns the number of bytes read (when nothing goes wrong).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top