如何获取读取的字节数
当我像这样从stdin读取时:
size_t bufSize = 1024;
unsigned char inputBuffer[bufSize];
size_t readNum = 0;
readNum = fread(inputBuffer, sizeof(unsigned char) * bufSize, 1, stdin);
在readNum中存储了对象的数量,这意味着当我从stdin读取1024字节时,readNum的值为1。但是当我从stdin读取时,readNum的值为1。 1024 字节,比 readNum 的值为 0。问题是,当数字小于 1024 时,如何识别从 stdin 读取了多少字节?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 readNum = fread(inputBuffer, sizeof(unsigned char), bufSize, stdin);
您正在尝试读取
bufSize
元素,每个元素都有一个大小sizeof( char)
- 不是一个大小为bufSize * sizeof(char)
的元素 - 因此您的fread
调用应该反映这一点。Use
readNum = fread(inputBuffer, sizeof(unsigned char), bufSize, stdin);
You're trying to read
bufSize
elements, each with a sizesizeof(char)
- not one element with a size ofbufSize * sizeof(char)
- so yourfread
call should reflect that.fread 读取给定大小的块并返回成功读取的块的数量。
如果要返回读取的字节数,请将块大小设置为 1,并将块数设置为要读取的字节数:
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: