IO

The IO class is the basis for all input and output in
Ruby. An I/O stream may be duplexed (that is, bidirectional), and
so may use more than one native operating system stream.

Many of the examples in this section use the File
class, the only standard subclass of IO. The two
classes are closely associated. Like the File
class, the Socket library subclasses from IO (such as
TCPSocket or UDPSocket).

The Kernel#open method can create
an IO (or File) object for
these types of arguments:

A plain string represents a filename suitable for the underlying operating
system.

A string starting with "|" indicates a subprocess.
The remainder of the string following the "|" is
invoked as a process with appropriate input/output channels connected to
it.

A string equal to "|-" will create another Ruby
instance as a subprocess.

The IO may be opened with different file modes
(read-only, write-only) and encodings for proper conversion. See ::new for these options. See Kernel#open for details of the various
command formats described above.

::popen, the Open3 library, or
Process#spawn may also be used to communicate with subprocesses through an
IO.

Ruby will convert pathnames between different operating system conventions
if possible. For instance, on a Windows system the filename
"/gumby/ruby/test.rb" will be opened as
"\gumby\ruby\test.rb". When specifying a
Windows-style filename in a Ruby string, remember to escape the
backslashes:

"c:\\gumby\\ruby\\test.rb"

Our examples here will use the Unix-style forward slashes;
File::ALT_SEPARATOR can be used to get the platform-specific separator
character.

The global constant ARGF (also accessible as $<)
provides an IO-like stream which allows access to all files mentioned on
the command line (or STDIN if no files are mentioned). ARGF#path and its alias ARGF#filename are provided to access
the name of the file currently being read.

Public Class Methods

binread(name, [length [, offset]] ) → stringclick to toggle source

Opens the file, optionally seeks to the given offset, then returns
length bytes (defaulting to the rest of the file).
binread ensures the file is closed before returning. The open
mode would be “rb:ASCII-8BIT”.

IO.binread("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"IO.binread("testfile", 20) #=> "This is line one\nThi"IO.binread("testfile", 20, 10) #=> "ne one\nThis is line "

"r" Read-only, starts at beginning of file (default mode).
"r+" Read-write, starts at beginning of file.
"w" Write-only, truncates existing file
to zero length or creates a new file for writing.
"w+" Read-write, truncates existing file to zero length
or creates a new file for reading and writing.
"a" Write-only, each write call appends data at end of file.
Creates a new file for writing if file does not exist.
"a+" Read-write, each write call appends data at end of file.
Creates a new file for reading and writing if file does
not exist.

The following modes must be used separately, and along with one or more of
the modes seen above.

When ext_enc is specified, strings read will be tagged by the
encoding when reading, and strings output will be converted to the
specified encoding when writing.

When ext_enc and int_enc are specified read
strings will be converted from ext_enc to int_enc
upon input, and written strings will be converted from int_enc
to ext_enc upon output. See Encoding for further details of transcoding on
input and output.

If “BOM|UTF-8”, “BOM|UTF-16LE” or “BOM|UTF16-BE” are used, ruby checks for
a Unicode BOM in the input document to help determine the encoding. For
UTF-16 encodings the file open mode must be binary. When present, the BOM
is stripped and the external encoding from the BOM is used. When the BOM
is missing the given Unicode encoding is used as ext_enc.
(The BOM-set encoding option is case insensitive, so “bom|utf-8” is also
valid.)

With no associated block, IO.open is a synonym for ::new. If the optional code block is
given, it will be passed io as an argument, and the IO object will automatically be closed when the block
terminates. In this instance, ::open
returns the value of the block.

Creates a pair of pipe endpoints (connected to each other) and returns them
as a two-element array of IO objects: [read_io, write_io].

If a block is given, the block is called and returns the value of the
block. read_io and write_io are sent to the block as
arguments. If read_io and write_io are not closed when the block exits,
they are closed. i.e. closing read_io and/or write_io doesn't cause an
error.

Not available on all platforms.

If an encoding (encoding name or encoding object) is specified as an
optional argument, read string from pipe is tagged with the encoding
specified. If the argument is a colon separated two encoding names “A:B”,
the read string is converted from encoding A (external encoding) to
encoding B (internal encoding), then tagged with B. If two optional
arguments are specified, those must be encoding objects or encoding names,
and the first one is the external encoding, and the second one is the
internal encoding. If the external encoding and the internal encoding is
specified, optional hash argument specify the conversion option.

In the example below, the two processes close the ends of the pipe that
they are not using. This is not just a cosmetic nicety. The read end of a
pipe will not generate an end of file condition if there are any writers
with the pipe still open. In the case of the parent process, the
rd.read will never return if it does not first issue a
wr.close.

If a block is given, Ruby will run the command as a child connected to Ruby
with a pipe. Ruby's end of the pipe will be passed as a parameter to
the block. At the end of block, Ruby closes the pipe and sets
$?. In this case IO.popen returns the value of
the block.

If a block is given with a cmd of “-'', the
block will be run in two separate processes: once in the parent, and once
in a child. The parent process will be passed the pipe object as a
parameter to the block, the child version of the block will be passed
nil, and the child's standard in and standard out will be
connected to the parent through the pipe. Not available on all platforms.

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

mode

string

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

open_args

array of strings

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"

Calls select(2) system call. It monitors given arrays of IO
objects, waits until one or more of IO objects are ready for
reading, are ready for writing, and have pending exceptions respectively,
and returns an array that contains arrays of those IO
objects. It will return nil if optional timeout
value is given and no IO object is ready in timeout
seconds.

IO.select peeks the buffer of IO objects for
testing readability. If the IO buffer is not empty,
IO.select immediately notifies readability. This “peek” only
happens for IO objects. It does not happen for IO-like objects
such as OpenSSL::SSL::SSLSocket.

The best way to use IO.select is invoking it after nonblocking
methods such as read_nonblock, write_nonblock,
etc. The methods raise an exception which is extended by
IO::WaitReadable or IO::WaitWritable. The modules
notify how the caller should wait with IO.select. If
IO::WaitReadable is raised, the caller should wait for
reading. If IO::WaitWritable is raised, the caller should wait
for writing.

So, blocking read (readpartial) can be emulated using
read_nonblock and IO.select as follows:

Especially, the combination of nonblocking methods and
IO.select is preferred for IO like objects such
as OpenSSL::SSL::SSLSocket. It has to_io method
to return underlying IO object. IO.select calls
to_io to obtain the file descriptor to wait.

This means that readability notified by IO.select doesn't
mean readability from OpenSSL::SSL::SSLSocket object.

The most likely situation is that OpenSSL::SSL::SSLSocket
buffers some data. IO.select doesn't see the buffer. So
IO.select can block when
OpenSSL::SSL::SSLSocket#readpartial doesn't block.

However, several more complicated situations exist.

SSL is a protocol which is sequence of records. The record consists of
multiple bytes. So, the remote side of SSL sends a partial record,
IO.select notifies readability but
OpenSSL::SSL::SSLSocket cannot decrypt a byte and
OpenSSL::SSL::SSLSocket#readpartial will blocks.

Also, the remote side can request SSL renegotiation which forces the local
SSL engine to write some data. This means
OpenSSL::SSL::SSLSocket#readpartial may invoke
write system call and it can block. In such a situation,
OpenSSL::SSL::SSLSocket#read_nonblock raises IO::WaitWritable instead of blocking. So,
the caller should wait for ready for writability as above example.

The combination of nonblocking methods and IO.select is also
useful for streams such as tty, pipe socket socket when multiple processes
read from a stream.

Finally, Linux kernel developers don't guarantee that readability of
select(2) means readability of following read(2) even for a single process.
See select(2) manual on GNU/Linux system.

Invoking IO.select before IO#readpartial works
well as usual. However it is not the best way to use
IO.select.

The writability notified by select(2) doesn't show how many bytes
writable. IO#write method blocks until given whole string is
written. So, IO#write(two or more bytes) can block after
writability is notified by IO.select.
IO#write_nonblock is required to avoid the blocking.

Blocking write (write) can be emulated using
write_nonblock and IO.select as follows: IO::WaitReadable should also be rescued for
SSL renegotiation in OpenSSL::SSL::SSLSocket.

Opens the file, optionally seeks to the given offset, writes
string, then returns the length written. write
ensures the file is closed before returning. If offset is not
given, the file is truncated. Otherwise, it is not truncated.

If the last argument is a hash, it specifies option for internal open().
The key would be the following. open_args: is exclusive to others.

encoding: string or encoding
specifies encoding of the read string. encoding will be ignored
if length is specified.
mode: string
specifies mode argument for open(). it should start with "w" or "a" or "r+"
otherwise it would cause error.
perm: integer
specifies perm argument for open().
open_args: array
specifies arguments for open() as an array.
IO.write("testfile", "0123456789", 20) # => 10
# File could contain: "This is line one\nThi0123456789two\nThis is line three\nAnd so on...\n"
IO.write("testfile", "0123456789") #=> 10
# File would now read: "0123456789"

Announce an intention to access data from the current file in a specific
pattern. On platforms that do not support the posix_fadvise(2)
system call, this method is a no-op.

advice is one of the following symbols:

:normal

No advice to give; the default assumption for an open file.

:sequential

The data will be accessed sequentially with lower offsets read before
higher ones.

:random

The data will be accessed in random order.

:willneed

The data will be accessed in the near future.

:dontneed

The data will not be accessed in the near future.

:noreuse

The data will only be accessed once.

The semantics of a piece of advice are platform-dependent. See man 2
posix_fadvise for details.

“data” means the region of the current file that begins at offset
and extends for len bytes. If len is 0, the region ends
at the last byte of the file. By default, both offset and
len are 0, meaning that the advice applies to the entire file.

If an error occurs, one of the following exceptions will be raised:

IOError

The IO stream is closed.

Errno::EBADF

The file descriptor of the current file is invalid.

Errno::EINVAL

An invalid value for advice was given.

Errno::ESPIPE

The file descriptor of the current file refers to a FIFO or pipe. (Linux
raises Errno::EINVAL in this case).

TypeError

Either advice was not a Symbol, or one
of the other arguments was not an Integer.

Closes ios and flushes any pending writes to the operating system.
The stream is unavailable for any further data operations; an
IOError is raised if such an attempt is made. I/O streams are
automatically closed when they are claimed by the garbage collector.

If ios is opened by IO.popen, close sets
$?.

Calling this method on closed IO object is just
ignored since Ruby 2.3.

Ruby sets close-on-exec flags of all file descriptors by default since Ruby
2.0.0. So you don't need to set by yourself. Also, unsetting a
close-on-exec flag can cause file descriptor leak if another thread use
fork() and exec() (via system() method for example). If you really needs
file descriptor inheritance to child process, use spawn()'s argument
such as fd=>fd.

Provides a mechanism for issuing low-level commands to control or query
file-oriented I/O streams. Arguments and results are platform dependent. If
arg is a number, its value is passed directly. If it is a string,
it is interpreted as a binary sequence of bytes (Array#pack
might be a useful way to build this string). On Unix platforms, see
fcntl(2) for details. Not implemented on all platforms.

Flushes any buffered data within ios to the underlying operating
system (note that this is Ruby internal buffering only; the OS may buffer
the data as well).

$stdout.print"no newline"$stdout.flush

produces:

nonewline

VALUE
rb_io_flush(VALUE io)
{
return rb_io_flush_raw(io, 1);
}

fsync → 0 or nilclick to toggle source

Immediately writes all buffered data in ios to disk. Note that
fsync differs from using IO#sync=. The latter
ensures that data is flushed from Ruby's buffers, but does not
guarantee that the underlying operating system actually writes it to disk.

NotImplementedError is raised if the underlying operating
system does not support fsync(2).

Reads the next “line'' from the I/O stream; lines are separated by
sep. A separator of nil reads the entire contents,
and a zero-length separator reads the input a paragraph at a time (two
successive newlines in the input separate paragraphs). The stream must be
opened for reading or an IOError will be raised. The line read
in will be returned and also assigned to $_. Returns
nil if called at end of file. If the first argument is an
integer, or optional second argument is given, the returning string would
not be longer than the given value in bytes.

File.new("testfile").gets#=> "This is line one\n"$_#=> "This is line one\n"File.new("testfile").gets(4)#=> "This"

Provides a mechanism for issuing low-level commands to control or query I/O
devices. Arguments and results are platform dependent. If arg is a
number, its value is passed directly. If it is a string, it is interpreted
as a binary sequence of bytes. On Unix platforms, see ioctl(2)
for details. Not implemented on all platforms.

Returns the current line number in ios. The stream must be opened
for reading. lineno counts the number of times gets is called rather than the number of
newlines encountered. The two values will differ if gets is called with a separator other than
newline.

Writes the given object(s) to ios. The stream must be opened for
writing. If the output field separator ($,) is not
nil, it will be inserted between each object. If the output
record separator ($\) is not nil, it will be
appended to the output. If no arguments are given, prints $_.
Objects that aren't strings will be converted by calling their
to_s method. With no argument, prints the contents of the
variable $_. Returns nil.

If obj is Numeric, write the character whose code is
the least-significant byte of obj, otherwise write the first byte
of the string representation of obj to ios. Note: This
method is not safe for use with multi-byte characters as it will truncate
them.

Writes the given objects to ios as with IO#print.
Writes a record separator (typically a newline) after any that do not
already end with a newline sequence. If called with an array argument,
writes each element on a new line. If called without arguments, outputs a
single record separator.

If length is a positive integer, it tries 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.

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.

Reads at most maxlen bytes from ios using the read(2)
system call after O_NONBLOCK is set for the underlying file descriptor.

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.

#read_nonblock just calls the
read(2) system call. It causes all errors the read(2) system call causes:
Errno::EWOULDBLOCK, Errno::EINTR, etc. The caller should care such errors.

If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN, it is extended by
IO::WaitReadable. So IO::WaitReadable can be used to rescue the
exceptions for retrying read_nonblock.

Reads all of the lines in ios, and returns them in
anArray. Lines are separated by the optional sep. If
sep is nil, the rest of the stream is returned as a
single record. If the first argument is an integer, or optional second
argument is given, the returning string would not be longer than the given
value in bytes. The stream must be opened for reading or an
IOError will be raised.

Reads at most maxlen bytes from the I/O stream. It blocks only if
ios has no data immediately available. It doesn't block if
some data available. 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. It raises
EOFError on end of file.

readpartial is designed for streams such as pipe, socket, tty, etc. It
blocks only when no data immediately available. This means that it blocks
only when following all conditions hold.

When readpartial blocks, it waits data or EOF on the stream. If some data
is reached, readpartial returns with the data. If EOF is reached,
readpartial raises EOFError.

When readpartial doesn't blocks, it returns or raises immediately. If
the byte buffer is not empty, it returns the data in the buffer. Otherwise
if the stream has some content, it returns the data in the stream.
Otherwise if the stream is reached to EOF, it raises EOFError.

Seeks to a given offset anInteger in the stream according to the
value of whence:

:CUR or IO::SEEK_CUR | Seeks to _amount_ plus current position
----------------------+--------------------------------------------------
:END or IO::SEEK_END | Seeks to _amount_ plus end of stream (you
| probably want a negative value for _amount_)
----------------------+--------------------------------------------------
:SET or IO::SEEK_SET | Seeks to the absolute location given by _amount_

If single argument is specified, read string from io is tagged with the
encoding specified. If encoding is a colon separated two encoding names
“A:B”, the read string is converted from encoding A (external encoding) to
encoding B (internal encoding), then tagged with B. If two arguments are
specified, those must be encoding objects or encoding names, and the first
one is the external encoding, and the second one is the internal encoding.
If the external encoding and the internal encoding is specified, optional
hash argument specify the conversion option.

Sets the “sync mode'' to true or false.
When sync mode is true, all output is immediately flushed to the underlying
operating system and is not buffered internally. Returns the new state. See
also IO#fsync.

Reads maxlen bytes from ios using a low-level read and
returns them as a string. Do not mix with other methods that read from
ios or you may get unpredictable results. 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. Raises
SystemCallError on error and EOFError at end of
file.

Writes the given string to ios using a low-level write. Returns
the number of bytes written. Do not mix with other methods that write to
ios or you may get unpredictable results. Raises
SystemCallError on error.

Pushes back bytes (passed as a parameter) onto ios, such that a
subsequent buffered read will return it. Only one byte may be pushed back
before a subsequent read operation (that is, you will be able to read only
the last of several bytes that have been pushed back). Has no effect with
unbuffered reads (such as IO#sysread).

Pushes back one character (passed as a parameter) onto ios, such
that a subsequent buffered character read will return it. Only one
character may be pushed back before a subsequent read operation (that is,
you will be able to read only the last of several characters that have been
pushed back). Has no effect with unbuffered reads (such as
IO#sysread).

Writes the given string to ios using the write(2) system call
after O_NONBLOCK is set for the underlying file descriptor.

It returns the number of bytes written.

#write_nonblock just calls
the write(2) system call. It causes all errors the write(2) system call
causes: Errno::EWOULDBLOCK, Errno::EINTR, etc. The result may also be
smaller than string.length (partial write). The caller should care such
errors and partial write.

If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN, it is extended by
IO::WaitWritable. So IO::WaitWritable can be used to rescue the
exceptions for retrying write_nonblock.