Ruby 文件 I/O 中的 EOFError 是什么?

发布于 2024-08-01 13:24:11 字数 166 浏览 6 评论 0原文

官方文档没有指定。 我理解 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 技术交流群。

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

发布评论

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

评论(2

浴红衣 2024-08-08 13:24:11

EOFError 在所有 IO 中都很方便,该类是 ruby​​ 中所有输入/输出的基础。 现在还请记住核心 Unix 概念:一切都是文件。 这包括套接字。 因此,如果您打开了某个套接字并正在从中读取数据,则异常情况可能是遇到文件结尾。

所有的例子都显示了 EOFError 的简单用法(在读取一些文本文件时),这并不是真正有用。 但是,开始深入研究 net/http 或其他大量使用套接字的类,您将看到正在使用此异常。

编辑以从 net/ftp 添加此示例

def getline
  line = @sock.readline # if get EOF, raise EOFError
  line.sub!(/(\r\n|\n|\r)\z/n, "")
  if @debug_mode
    print "get: ", sanitize(line), "\n"
  end
  return line
end

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

def getline
  line = @sock.readline # if get EOF, raise EOFError
  line.sub!(/(\r\n|\n|\r)\z/n, "")
  if @debug_mode
    print "get: ", sanitize(line), "\n"
  end
  return line
end
冷夜 2024-08-08 13:24:11

当您尝试对已经引用文件末尾的文件对象执行操作时,会引发 EOFError(文件结束错误)。 在此示例中,当该行不存在时,我们尝试读取该行。

例如:

import_file = File.open(filename)
begin
  while (line = import_file.readline)
    sline = FasterCSV.parse_line(line)
    # Do stuff with sline
  end
rescue EOFError
  # Finished processing the file
end

没有 EOFError 也可以实现同样的效果:

File.open(filename).each do |line|
    sline = FasterCSV.parse_line(line)
    # Do stuff with sline        
end

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:

import_file = File.open(filename)
begin
  while (line = import_file.readline)
    sline = FasterCSV.parse_line(line)
    # Do stuff with sline
  end
rescue EOFError
  # Finished processing the file
end

The same thing can be achieved without the EOFError:

File.open(filename).each do |line|
    sline = FasterCSV.parse_line(line)
    # Do stuff with sline        
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文