What is an EOFError in Ruby file I/O?
Asked Answered
C

2

13

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.

Capybara answered 13/8, 2009 at 14:41 Comment(0)
P
20

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
Petty answered 13/8, 2009 at 15:29 Comment(1)
Thanks Swanand. I owe the example code to my favourite use of find... "find /usr/lib/ruby/1.8/net/ -name *.rb -exec grep EOFError /dev/null '{}' \;"Petty
P
9

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
Pepsinate answered 13/8, 2009 at 14:57 Comment(3)
thanks for the response. i understand EOFError means "End of file error". but what exactly does that mean? If the reader reaches the end of the file, that doesn't sound like an error to me.Capybara
Sorry, how stupid of me to not consider. I updated the answer, but I guess it still may not answer your question.Pepsinate
if those two are pretty much equivalent for file handling, helps a bit. thanksCapybara

© 2022 - 2024 — McMap. All rights reserved.