如何FREAD真的有用吗? [英] How does fread really work?

查看:170
本文介绍了如何FREAD真的有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FREAD 的声明如下:

 为size_t FREAD(无效* PTR,为size_t长度size_t nmemb个,FILE *流);

现在的问题是:有没有在读两个这样的呼叫性能差异 FREAD

 字符一[1000];


  1. FREAD(一,1,1000,标准输入);

  2. FREAD(一,1000,1,标准输入);

将它读 1000 字节的一次的每一次?


解决方案

有可能会或可能不会在任何性能差异。语义方面的差异。

  FREAD(一,1,1000,标准输入);

试图读取1000个数据元素,其每一个是1字节长。

  FREAD(一,1000,1,标准输入);

尝试读取这是1000字节长1数据元素。

他们是不同的,因为 FREAD()返回它能够读取,而不是字节数的数据元素的数量。如果读满1000字节前到达档案结尾(或错误),第一个版本已经表明它到底有多少字节读取;第二只是将失败并返回0。

在实践中,它可能只是要打电话试图读取1000字节,表示多少字节它实际读取下级功能。对于较大的读取,它可能使多个低级调用。通过 FREAD返回的值的计算()是不同的,但计算的代价实在是微不足道。

有可能是一个区别,如果实施可以告诉,试图读取数据之前,有没有足够的数据来读取。例如,如果你从一个900字节的文件中读取,第一个版本将读取所有的900字节,并返回900,而第二个可能懒得读什么。在这两种情况下,该文件的位置指示器被数先进的字符的成功读取,即900

但在一般情况下,你应该选择如何根据你从它需要什么信息来调用它。读一个单一的数据元素,如果部分读取并不比不读什么都好。阅读小块,如果局部读取是有用的。

The declaration of fread is as following:

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

The question is: Is there a difference in reading performance of two such calls to fread:

char a[1000];

  1. fread(a, 1, 1000, stdin);
  2. fread(a, 1000, 1, stdin);

Will it read 1000 bytes at once each time?

解决方案

There may or may not be any difference in performance. There is a difference in semantics.

fread(a, 1, 1000, stdin);

attempts to read 1000 data elements, each of which is 1 byte long.

fread(a, 1000, 1, stdin);

attempts to read 1 data element which is 1000 bytes long.

They're different because fread() returns the number of data elements it was able to read, not the number of bytes. If it reaches end-of-file (or an error condition) before reading the full 1000 bytes, the first version has to indicate exactly how many bytes it read; the second just fails and returns 0.

In practice, it's probably just going to call a lower-level function that attempts to read 1000 bytes and indicates how many bytes it actually read. For larger reads, it might make multiple lower-level calls. The computation of the value to be returned by fread() is different, but the expense of the calculation is trivial.

There may be a difference if the implementation can tell, before attempting to read the data, that there isn't enough data to read. For example, if you're reading from a 900-byte file, the first version will read all 900 bytes and return 900, while the second might not bother to read anything. In both cases, the file position indicator is advanced by the number of characters successfully read, i.e., 900.

But in general, you should probably choose how to call it based on what information you need from it. Read a single data element if a partial read is no better than not reading anything at all. Read in smaller chunks if partial reads are useful.

这篇关于如何FREAD真的有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆