fgets() 和 fread() - 有什么区别?
我了解 fgets()
和 fgetss()
但我不明白 之间的区别fgets()
和 fread()
,有人可以澄清这个问题吗?哪一个更快?谢谢!
I understand the differences between fgets()
and fgetss()
but I don't get the difference between fgets()
and fread()
, can someone please clarify this subject? Which one is faster? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
fgets
读取 < strong>一行——即它将停在换行符处。fread
读取 <强>原始数据——它将在指定的(或默认)字节数后停止,与可能存在或不存在的任何换行符无关。速度不是使用一个的原因,因为这两个函数不做同样的事情:
fgets
fread
。fgets
reads a line -- i.e. it will stop at a newline.fread
reads raw data -- it will stop after a specified (or default) number of bytes, independently of any newline that might or might not be present.Speed is not a reason to use one over the other, as those two functions just don't do the same thing :
fgets
fread
.fread() 用于二进制数据,fread 对可以读取的字符数有限制,
数字 5 是已读取的长度字节。
fread() for binary data and fread has a limit on how many chars you can read
Number 5 is length bytes have been read .
函数 fgets 从文本文件中读取一行。它读取的时间很长,直到到达当前行的末尾(或文件的末尾)。因此,如果您想从文本文件中读取一行,您应该使用 fgets。
函数 fread 不仅读取到行尾,而且读取到文件末尾[例如 fread($handle)] 或与参数指定的字节数[例如 fread($handle, 1024)]。因此,如果您想读取完整的文件,无论它是包含所有行的文本文件还是文件中的任意原始数据,您都应该使用 fread。
The function fgets reads a single line from a text file. It is reading so long until the end of the current line (or the end of the file) is reached. Therefore, if you would like to read one line from a text file, you should use fgets.
The function fread not only reads until the end of the line but to the end of the file [e.g. fread($handle)] or as many bytes as specified as a parameter [e.g. fread($handle, 1024)]. So, if you would like to read a complete file, no matter whether it is a text file with all containing lines or arbitrary raw data from a file, you should use fread.
这两个函数都用于从文件中读取数据
fgets($filename, $bytes)
fgets 通常读取 $bytes-1 数量的数据,并在换行符或 EOF(文件结束符)处停止,以先到者为准。如果未指定字节,则默认值为 1024 字节。
fread($文件名,$字节)
fread 精确读取 $bytes 数量的数据并仅在 EOF 处停止。
Both the functions are used to read data from files
fgets($filename, $bytes)
fgets usually reads $bytes-1 amount of data and stops at a newline or an EOF(end-of-file) whichever comes first. If the bytes are not specified, then the default value is 1024 bytes.
fread($filename, $bytes)
fread reads exactly $bytes amount of data and stops only at EOF.
接受的答案是正确的,但还有一种情况会导致
fread
停止阅读。fread
的块限制为 8192 字节。当我从fread($stream, 8300)
和fget($stream, 8300)
获得不同的结果时,我发现了这一点。来自
fread
文档:The accepted answer is correct, but there is one more case for
fread
to stop reading.fread
has a chunk limit of 8192 bytes. I discovered this when I was getting different results fromfread($stream, 8300)
andfget($stream, 8300)
.From
fread
docs: