read 2

ios.read([length [, outbuf]]) รข string, outbuf, or nil
Instance Public methods

Reads length bytes from the I/O stream.

length must be a non-negative integer or nil.

If length is a positive integer, it try to read length bytes without any conversion (binary mode). It returns nil or a string whose length is 1 to length bytes. nil means it met EOF at beginning. The 1 to length-1 bytes string means it met EOF after reading the result. The length bytes string means it doesn't meet EOF. The resulted string is always ASCII-8BIT encoding.

If length is omitted or is nil, it reads until EOF and the encoding conversion is applied. It returns a string even if EOF is met at beginning.

If length is zero, it returns "".

If the optional outbuf argument is present, it must reference a String, which will receive the data. The outbuf will contain only the received data after the method call even if it is not empty at the beginning.

At end of file, it returns nil or "" depend on length. ios.read() and ios.read(nil) returns "". ios.read(positive-integer) returns nil.

f = File.new("testfile")
f.read(16)   #=> "This is line one"

# reads whole file
open("file") {|f|
  data = f.read # This returns a string even if the file is empty.
  ...
}

# iterate over fixed length records.
open("fixed-record-file") {|f|
  while record = f.read(256)
    ...
  end
}

# iterate over variable length records.
# record is prefixed by 32-bit length.
open("variable-record-file") {|f|
  while len = f.read(4)
    len = len.unpack("N")[0] # 32-bit length
    record = f.read(len) # This returns a string even if len is 0.
  end
}

Note that this method behaves like fread() function in C. This means it retry to invoke read(2) system call to read data with the specified length (or until EOF). This behavior is preserved even if ios is non-blocking mode. (This method is non-blocking flag insensitive as other methods.) If you need the behavior like single read(2) system call, consider readpartial, #read_nonblock and sysread.

doc_ruby_on_rails
2015-04-13 13:31:21
Comments
Leave a Comment

Please login to continue.