Method: IO.read

Defined in:
io.c

.read(name, [length [, offset]][, opt]) ⇒ String

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). #read ensures the file is closed before returning.

If name starts with a pipe character ("|"), a subprocess is created in the same way as Kernel#open, and its output is returned.

Options

The options hash accepts the following keys:

:encoding

string or encoding

Specifies the encoding of the read string. :encoding will be ignored if length is specified. See Encoding.aliases for possible encodings.

:mode

string or integer

Specifies the mode argument for open(). It must start with an “r”, otherwise it will cause an error. See IO.new for the list of possible modes.

:open_args

array

Specifies arguments for open() as an array. This key can not be used in combination with either :encoding or :mode.

Examples:

IO.read("testfile")              #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
IO.read("testfile", 20)          #=> "This is line one\nThi"
IO.read("testfile", 20, 10)      #=> "ne one\nThis is line "
IO.read("binfile", mode: "rb")   #=> "\xF7\x00\x00\x0E\x12"

Returns:



10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
# File 'io.c', line 10759

static VALUE
rb_io_s_read(int argc, VALUE *argv, VALUE io)
{
    VALUE opt, offset;
    struct foreach_arg arg;

    argc = rb_scan_args(argc, argv, "13:", NULL, NULL, &offset, NULL, &opt);
    open_key_args(io, argc, argv, opt, &arg);
    if (NIL_P(arg.io)) return Qnil;
    if (!NIL_P(offset)) {
	struct seek_arg sarg;
	int state = 0;
	sarg.io = arg.io;
	sarg.offset = offset;
	sarg.mode = SEEK_SET;
	rb_protect(seek_before_access, (VALUE)&sarg, &state);
	if (state) {
	    rb_io_close(arg.io);
	    rb_jump_tag(state);
	}
	if (arg.argc == 2) arg.argc = 1;
    }
    return rb_ensure(io_s_read, (VALUE)&arg, rb_io_close, arg.io);
}