开发者

how to get number of read bytes

开发者 https://www.devze.com 2023-02-25 10:28 出处:网络
when I read from st开发者_开发知识库din like this: size_t bufSize = 1024; unsigned char inputBuffer[bufSize];

when I read from st开发者_开发知识库din 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?


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消