read(p1 = v1, p2 = v2)
public
Reads at most length bytes from the
I/O stream, or to the end of file if length is omitted or is nil.
length must be a non-negative integer or nil. If the optional
buffer argument is present, it must reference a String, which will receive the data.
At end of file, it returns nil or “” depend on length.
ios.read() and ios.read(nil) returns “”. ios.read(positive-integer) returns nil.
ios.read(0) returns “”.
f = File.new("testfile")
f.read(16)
Show source
static VALUE
io_read(int argc, VALUE *argv, VALUE io)
{
rb_io_t *fptr;
long n, len;
VALUE length, str;
rb_scan_args(argc, argv, "02", &length, &str);
if (NIL_P(length)) {
if (!NIL_P(str)) StringValue(str);
GetOpenFile(io, fptr);
rb_io_check_readable(fptr);
return read_all(fptr, remain_size(fptr), str);
}
len = NUM2LONG(length);
if (len < 0) {
rb_raise(rb_eArgError, "negative length %ld given", len);
}
if (NIL_P(str)) {
str = rb_str_new(0, len);
}
else {
StringValue(str);
rb_str_modify(str);
rb_str_resize(str,len);
}
GetOpenFile(io, fptr);
rb_io_check_readable(fptr);
if (len == 0) return str;
READ_CHECK(fptr);
if (RSTRING_LEN(str) != len) {
rb_raise(rb_eRuntimeError, "buffer string modified");
}
n = io_fread(str, 0, fptr);
if (n == 0) {
if (fptr->fd < 0) return Qnil;
rb_str_resize(str, 0);
return Qnil;
}
rb_str_resize(str, n);
OBJ_TAINT(str);
return str;
}