Ruby 文件 I/O 中的 EOFError 是什么?
官方文档没有指定。 我理解 EOFError 的意思是“文件结束错误”,但这到底意味着什么? 如果文件读取器到达文件末尾,对我来说这听起来不像是错误。
The official documentation doesn't specify. I understand EOFError means "End of file error", but what exactly does that mean? If a file reader reaches the end of a file, that doesn't sound like an error to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EOFError 在所有 IO 中都很方便,该类是 ruby 中所有输入/输出的基础。 现在还请记住核心 Unix 概念:一切都是文件。 这包括套接字。 因此,如果您打开了某个套接字并正在从中读取数据,则异常情况可能是遇到文件结尾。
所有的例子都显示了 EOFError 的简单用法(在读取一些文本文件时),这并不是真正有用。 但是,开始深入研究 net/http 或其他大量使用套接字的类,您将看到正在使用此异常。
编辑以从 net/ftp 添加此示例
EOFError is handy in all of IO, the class which is the basis of all input/output in ruby. Now also remember core Unix concepts: everything is a file. This includes sockets. So, if you have some socket open and are reading from it, an exceptional condition might be to encounter an end of file.
All the examples out there show trivial uses of EOFError (while reading some text file), which are not really useful. However, start digging through net/http or other classes which use sockets heavily, and you'll see this exception being used.
Edited to add this example from net/ftp
当您尝试对已经引用文件末尾的文件对象执行操作时,会引发 EOFError(文件结束错误)。 在此示例中,当该行不存在时,我们尝试读取该行。
例如:
没有 EOFError 也可以实现同样的效果:
EOFError (End of File error), is thrown when you trying to do carry out an operation on a file object that has already referencing to the end of the file. In this example, we are trying to
readline
when the line doesn't exist.For example:
The same thing can be achieved without the EOFError: