c4757p
c4757p

Reputation: 1808

Number of bytes read from a pipe

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

Answers (2)

dwc
dwc

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

Bastien Léonard
Bastien Léonard

Reputation: 61713

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

Upvotes: 1

Related Questions