如何获取读取的字节数

发布于 2024-11-01 17:59:25 字数 349 浏览 1 评论 0原文

当我像这样从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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

神回复 2024-11-08 17:59:25

使用 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 size sizeof(char) - not one element with a size of bufSize * sizeof(char) - so your fread call should reflect that.

听风吹 2024-11-08 17:59:25
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

fread 读取给定大小的块并返回成功读取的块的数量。
如果要返回读取的字节数,请将块大小设置为 1,并将块数设置为要读取的字节数:

readNum = fread(inputBuffer, 1, sizeof(unsigned char) * bufSize, stdin);
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);
故事还在继续 2024-11-08 17:59:25
readNum = fread(inputBuffer, 1, sizeof(unsigned char)*bufSize, stdin);
readNum = fread(inputBuffer, 1, sizeof(unsigned char)*bufSize, stdin);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文