pierre tautou
pierre tautou

Reputation: 817

how to get number of read bytes

when I read from stdin like this:

size_t bufSize = 1024;
unsigned char inputBuffer[bufSize];
size_t readNum = 0;
readNum = fread(inputBuffer, sizeof(unsigned char) * bufSize, 1, stdin);

in the readNum are stored number of object, this mean when I read from stdin 1024 bytes, the readNum has value 1. But when I read from stdin < 1024 bytes, than readNum has value 0. Question is, how can I recognize how many bytes was read from stdin when the number is less then 1024?

Upvotes: 2

Views: 9101

Answers (3)

fnokke
fnokke

Reputation: 1161

readNum = fread(inputBuffer, 1, sizeof(unsigned char)*bufSize, stdin);

Upvotes: 0

Erik
Erik

Reputation: 91270

Use readNum = fread(inputBuffer, sizeof(unsigned char), bufSize, stdin);

You're trying to read bufSize elements, each with a size sizeof(char) - not one element with a size of bufSize * sizeof(char) - so your fread call should reflect that.

Upvotes: 3

codymanix
codymanix

Reputation: 29468

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

fread reads blocks with the given size and returns the number of sucessfully read blocks. If you want to return the number of bytes read then set the blocksize to 1 and the number of blocks to the number of bytes you want to read:

readNum = fread(inputBuffer, 1, sizeof(unsigned char) * bufSize, stdin);

Upvotes: 1

Related Questions