Reading Files in Ruby

Reading and writing files are basic tasks needed for many Ruby programs. First we’ll look at some examples of reading files.

# Reading files requires checking most calls for errors.
# This helper will streamline our error checks below.
def check(error)
  raise error if error
end

# Perhaps the most basic file reading task is
# slurping a file's entire contents into memory.
dat = File.read("/tmp/dat")
puts dat

# You'll often want more control over how and what
# parts of a file are read. For these tasks, start
# by opening a file to obtain a File object.
File.open("/tmp/dat", "r") do |f|
  # Read some bytes from the beginning of the file.
  # Allow up to 5 to be read but also note how many
  # actually were read.
  b1 = f.read(5)
  puts "#{b1.size} bytes: #{b1}"

  # You can also seek to a known location in the file
  # and read from there.
  f.seek(6, IO::SEEK_SET)
  b2 = f.read(2)
  puts "#{b2.size} bytes @ 6: #{b2}"

  # Other methods of seeking are relative to the
  # current cursor position,
  f.seek(4, IO::SEEK_CUR)

  # and relative to the end of the file.
  f.seek(-10, IO::SEEK_END)

  # The StringIO class provides some functions that may
  # be helpful for file reading. For example, reads
  # like the ones above can be more robustly
  # implemented with readpartial.
  f.seek(6, IO::SEEK_SET)
  b3 = f.readpartial(2)
  puts "#{b3.size} bytes @ 6: #{b3}"

  # There is no built-in rewind, but
  # seek(0, IO::SEEK_SET) accomplishes this.
  f.seek(0, IO::SEEK_SET)

  # The StringIO class implements a buffered
  # reader that may be useful both for its efficiency
  # with many small reads and because of the additional
  # reading methods it provides.
  r4 = StringIO.new(f.read)
  b4 = r4.read(5)
  puts "5 bytes: #{b4}"

  # The file will be automatically closed when the block ends
end

To run the program:

$ echo "hello" > /tmp/dat
$ echo "ruby" >>   /tmp/dat
$ ruby reading-files.rb
hello
ruby
5 bytes: hello
2 bytes @ 6: ru
2 bytes @ 6: ru
5 bytes: hello

Next we’ll look at writing files.