Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

IO.read

(::path name, ?::Integer? length, ?::Integer offset, ?external_encoding: ::String | ::Encoding | nil, ?internal_encoding: ::String | ::Encoding | nil, ?encoding: ::String | ::Encoding | nil, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?mode: ::String) -> ::String
IO.read(path, length = nil, offset = 0, **opts) → string or nil

Opens the stream, reads and returns some or all of its content, and closes the stream; returns nil if no bytes were read.

The first argument must be a string that is the path to a file.

With only argument path given, reads in text mode and returns the entire content of the file at the given path:

Example
File.read('t.txt')
# => "First line\nSecond line\n\nFourth line\nFifth line\n"
File.read('t.ja')
# => "こんにちは"
File.read('t.dat')
# => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"

On Windows, text mode can terminate reading and leave bytes in the file unread when encountering certain special bytes. Consider using IO.binread if all bytes in the file should be read.

With argument length, returns length bytes if available:

Example
File.read('t.txt', 7)
# => "First l"
File.read('t.ja', 7)
# => "\xE3\x81\x93\xE3\x82\x93\xE3"
File.read('t.dat', 7)
# => "\xFE\xFF\x99\x90\x99\x91\x99"

Returns all bytes if length is larger than the files size:

Example
File.read('t.txt', 700)
# => "First line\r\nSecond line\r\n\r\nFourth line\r\nFifth line\r\n"
File.read('t.ja', 700)
# => "\xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1\xE3\x81\xAF"
File.read('t.dat', 700)
# => "\xFE\xFF\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"

With arguments length and offset, returns length bytes if available, beginning at the given offset:

Example
File.read('t.txt', 10, 2)
# => "rst line\r\n"
File.read('t.ja', 10, 2)
# => "\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1"
File.read('t.dat', 10, 2)
# => "\x99\x90\x99\x91\x99\x92\x99\x93\x99\x94"

Returns nil if offset is past the end of the stream:

Example
File.read('t.txt', 10, 200)
# => nil

Optional keyword arguments opts specify:

See also #read .popen .readlines .pipe also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0