Class

Expect library adds the IO instance method expect, which does similar act to tcl's expect extension.

In order to use this method, you must require expect:

require 'expect'

Please see expect for usage.

An instance of class IO (commonly called a stream) represents an input/output stream in the underlying operating system. Class IO is the basis for input and output in Ruby.

Class File is the only class in the Ruby core that is a subclass of IO. Some classes in the Ruby standard library are also subclasses of IO; these include TCPSocket and UDPSocket.

The global constant ARGF (also accessible as $<) provides an IO-like stream that allows access to all file paths found in ARGV (or found in STDIN if ARGV is empty). Note that ARGF is not itself a subclass of IO.

Important objects based on IO include:

  • $stdin.

  • $stdout.

  • $stderr.

  • Instances of class File.

An instance of IO may be created using:

  • IO.new: returns a new IO object for the given integer file descriptor.

  • IO.open: passes a new IO object to the given block.

  • IO.popen: returns a new IO object that is connected to the $stdin and $stdout of a newly-launched subprocess.

  • Kernel#open: Returns a new IO object connected to a given source: stream, file, or subprocess.

A IO stream has:

  • A read/write mode, which may be read-only, write-only, or read/write; see Read/Write Mode.

  • A data mode, which may be text-only or binary; see Data Mode.

  • A position, which determines where in the stream the next read or write is to occur; see Position.

  • A line number, which is a special, line-oriented, “position” (different from the position mentioned above); see Line Number.

  • Internal and external encodings; see Encodings.

Extension io/console

Extension io/console provides numerous methods for interacting with the console; requiring it adds numerous methods to class IO.

Example Files

Many examples here use these filenames and their corresponding files:

  • t.txt: A text-only file that is assumed to exist via:

    text = <<~EOT
      First line
      Second line
    
      Fourth line
      Fifth line
    EOT
    File.write('t.txt', text)
    
  • t.dat: A data file that is assumed to exist via:

    data = "\u9990\u9991\u9992\u9993\u9994"
    f = File.open('t.dat', 'wb:UTF-16')
    f.write(data)
    f.close
    
  • t.rus: A Russian-language text file that is assumed to exist via:

    File.write('t.rus', "\u{442 435 441 442}")
    
  • t.tmp: A file that is assumed not to exist.

Modes

A number of IO method calls must or may specify a mode for the stream; the mode determines how stream is to be accessible, including:

  • Whether the stream is to be read-only, write-only, or read-write.

  • Whether the stream is positioned at its beginning or its end.

  • Whether the stream treats data as text-only or binary.

  • The external and internal encodings.

Read/Write Mode

Read/Write Mode Specified as an Integer

When mode is an integer it must be one or more (combined by bitwise OR (|) of the modes defined in File::Constants:

  • File::RDONLY: Open for reading only.

  • File::WRONLY: Open for writing only.

  • File::RDWR: Open for reading and writing.

  • File::APPEND: Open for appending only.

  • File::CREAT: Create file if it does not exist.

  • File::EXCL: Raise an exception if File::CREAT is given and the file exists.

Examples:

File.new('t.txt', File::RDONLY)
File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)

Note: Method IO#set_encoding does not allow the mode to be specified as an integer.

Read/Write Mode Specified As a String

When mode is a string it must begin with one of the following:

  • 'r': Read-only stream, positioned at the beginning; the stream cannot be changed to writable.

  • 'w': Write-only stream, positioned at the beginning; the stream cannot be changed to readable.

  • 'a': Write-only stream, positioned at the end; every write appends to the end; the stream cannot be changed to readable.

  • 'r+': Read-write stream, positioned at the beginning.

  • 'w+': Read-write stream, positioned at the end.

  • 'a+': Read-write stream, positioned at the end.

For a writable file stream (that is, any except read-only), the file is truncated to zero if it exists, and is created if it does not exist.

Examples:

File.open('t.txt', 'r')
File.open('t.tmp', 'w')

Data Mode

Either of the following may be suffixed to any of the string read/write modes above:

  • 't': Text data; sets the default external encoding to Encoding::UTF_8; on Windows, enables conversion between EOL and CRLF.

  • 'b': Binary data; sets the default external encoding to Encoding::ASCII_8BIT; on Windows, suppresses conversion between EOL and CRLF.

If neither is given, the stream defaults to text data.

Examples:

File.open('t.txt', 'rt')
File.open('t.dat', 'rb')

The following may be suffixed to any writable string mode above:

  • 'x': Creates the file if it does not exist; raises an exception if the file exists.

Example:

File.open('t.tmp', 'wx')

Encodings

Any of the string modes above may specify encodings – either external encoding only or both external and internal encodings – by appending one or both encoding names, separated by colons:

f = File.new('t.dat', 'rb')
f.external_encoding # => #<Encoding:ASCII-8BIT>
f.internal_encoding # => nil
f = File.new('t.dat', 'rb:UTF-16')
f.external_encoding # => #<Encoding:UTF-16 (dummy)>
f.internal_encoding # => nil
f = File.new('t.dat', 'rb:UTF-16:UTF-16')
f.external_encoding # => #<Encoding:UTF-16 (dummy)>
f.internal_encoding # => #<Encoding:UTF-16>

The numerous encoding names are available in array Encoding.name_list:

Encoding.name_list.size    # => 175
Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]

When the external encoding is set, strings read are tagged by that encoding when reading, and strings written are converted to that encoding when writing.

When both external and internal encodings are set, strings read are converted from external to internal encoding, and strings written are converted from internal to external encoding. For further details about transcoding input and output, see Encoding.

If the external encoding is 'BOM|UTF-8', 'BOM|UTF-16LE' or 'BOM|UTF16-BE', 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. If the BOM is found, it is stripped and the external encoding from the BOM is used.

Note that the BOM-style encoding option is case insensitive, so 'bom|utf-8' is also valid.)

Open Options

A number of IO methods accept optional keyword arguments that determine how a new stream is to be opened:

  • :mode: Stream mode.

  • :flags: Integer file open flags; If mode is also given, the two are bitwise-ORed.

  • :external_encoding: External encoding for the stream.

  • :internal_encoding: Internal encoding for the stream. '-' is a synonym for the default internal encoding. If the value is nil no conversion occurs.

  • :encoding: Specifies external and internal encodings as 'extern:intern'.

  • :textmode: If a truthy value, specifies the mode as text-only, binary otherwise.

  • :binmode: If a truthy value, specifies the mode as binary, text-only otherwise.

  • :autoclose: If a truthy value, specifies that the fd will close when the stream closes; otherwise it remains open.

Also available are the options offered in String#encode, which may control conversion between external internal encoding.

Line Options

A number of IO methods accept optional keyword arguments that determine how lines in a stream are to be treated:

  • :chomp: If true, line separators are omitted; default is false.

Position

An IO stream has a position, which is the non-negative integer offset (in bytes) in the stream where the next read or write will occur.

Note that a text stream may have multi-byte characters, so a text stream whose position is n (bytes) may not have n characters preceding the current position – there may be fewer.

A new stream is initially positioned:

  • At the beginning (position 0) if its mode is 'r', 'w', or 'r+'.

  • At the end (position self.size) if its mode is 'a', 'w+', or 'a+'.

Methods to query the position:

  • IO#tell and its alias IO#pos return the position for an open stream.

  • IO#eof? and its alias IO#eof return whether the position is at the end of a readable stream.

Reading from a stream usually changes its position:

f = File.open('t.txt')
f.tell     # => 0
f.readline # => "This is line one.\n"
f.tell     # => 19
f.readline # => "This is the second line.\n"
f.tell     # => 45
f.eof?     # => false
f.readline # => "Here's the third line.\n"
f.eof?     # => true

Writing to a stream usually changes its position:

f = File.open('t.tmp', 'w')
f.tell         # => 0
f.write('foo') # => 3
f.tell         # => 3
f.write('bar') # => 3
f.tell         # => 6

Iterating over a stream usually changes its position:

f = File.open('t.txt')
f.each do |line|
  p "position=#{f.pos} eof?=#{f.eof?} line=#{line}"
end

Output:

"position=19 eof?=false line=This is line one.\n"
"position=45 eof?=false line=This is the second line.\n"
"position=70 eof?=true line=This is the third line.\n"

The position may also be changed by certain other methods:

Lines

Some reader methods in IO are line-oriented; such a method reads one or more lines, which are separated by an implicit or explicit line separator.

These methods include:

Each of these methods may be called with:

  • An optional line separator, sep.

  • An optional line-size limit, limit.

  • Both sep and limit.

Line Separator

The default line separator is the given by the global variable $/, whose value is often "\n". The line to be read next is all data from the current position to the next line separator:

f = File.open('t.txt')
f.gets # => "First line\n"
f.gets # => "Second line\n"
f.gets # => "\n"
f.gets # => "Fourth line\n"
f.gets # => "Fifth line\n"

You can specify a different line separator:

f = File.new('t.txt')
f.gets('l')   # => "First l"
f.gets('li')  # => "ine\nSecond li"
f.gets('lin') # => "ne\n\nFourth lin"
f.gets        # => "e\n"

There are two special line separators:

  • nil: The entire stream is read into a single string:

    f = File.new('t.txt')
    f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
    
  • '' (the empty string): The next “paragraph” is read (paragraphs being separated by two consecutive line separators):

    f = File.new('t.txt')
    f.gets('') # => "First line\nSecond line\n\n"
    f.gets('') # => "Fourth line\nFifth line\n"
    

Line Limit

The line to be read may be further defined by an optional argument limit, which specifies that the line may not be (much) longer than the given limit; a multi-byte character will not be split, and so a line may be slightly longer than the given limit.

If limit is not given, the line is determined only by sep.

# Text with 1-byte characters.
File.open('t.txt') {|f| f.gets(1) }  # => "F"
File.open('t.txt') {|f| f.gets(2) }  # => "Fi"
File.open('t.txt') {|f| f.gets(3) }  # => "Fir"
File.open('t.txt') {|f| f.gets(4) }  # => "Firs"
# No more than one line.
File.open('t.txt') {|f| f.gets(10) } # => "First line"
File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
File.open('t.txt') {|f| f.gets(12) } # => "First line\n"

# Text with 2-byte characters, which will not be split.
File.open('t.rus') {|f| f.gets(1).size } # => 1
File.open('t.rus') {|f| f.gets(2).size } # => 1
File.open('t.rus') {|f| f.gets(3).size } # => 2
File.open('t.rus') {|f| f.gets(4).size } # => 2

With arguments sep and limit given, combines the two behaviors:

  • Returns the next line as determined by line separator sep, or nil if none.

  • But returns no more bytes than are allowed by the limit.

Line Number

A readable IO stream has a line number, which is the non-negative integer line number in the stream where the next read will occur.

A new stream is initially has line number 0.

Method IO#lineno returns the line number.

Reading lines from a stream usually changes its line number:

f = File.open('t.txt', 'r')
f.lineno   # => 0
f.readline # => "This is line one.\n"
f.lineno   # => 1
f.readline # => "This is the second line.\n"
f.lineno   # => 2
f.readline # => "Here's the third line.\n"
f.lineno   # => 3
f.eof?     # => true

Iterating over lines in a stream usually changes its line number:

f = File.open('t.txt')
f.each_line do |line|
  p "position=#{f.pos} eof?=#{f.eof?} line=#{line}"
end

Output:

"position=19 eof?=false line=This is line one.\n"
"position=45 eof?=false line=This is the second line.\n"
"position=70 eof?=true line=This is the third line.\n"

What's Here

First, what's elsewhere. Class IO:

Here, class IO provides methods that are useful for:

Creating

  • ::new (aliased as ::for_fd)

    Creates and returns a new IO object for the given integer file descriptor.

  • ::open

    Creates a new IO object.

  • ::pipe

    Creates a connected pair of reader and writer IO objects.

  • ::popen

    Creates an IO object to interact with a subprocess.

  • ::select

    Selects which given IO instances are ready for reading,

    writing, or have pending exceptions.

Reading

  • ::binread

    Returns a binary string with all or a subset of bytes from the given file.

  • ::read

    Returns a string with all or a subset of bytes from the given file.

  • ::readlines

    Returns an array of strings, which are the lines from the given file.

  • getbyte

    Returns the next 8-bit byte read from self as an integer.

  • getc

    Returns the next character read from self as a string.

  • gets

    Returns the line read from self.

  • pread

    Returns all or the next n bytes read from self, not updating the receiver's offset.

  • read

    Returns all remaining or the next n bytes read from self for a given n.

  • read_nonblock

    the next n bytes read from self for a given n, in non-block mode.

  • readbyte

    Returns the next byte read from self; same as getbyte, but raises an exception on end-of-file.

  • readchar

    Returns the next character read from self; same as getc, but raises an exception on end-of-file.

  • readline

    Returns the next line read from self; same as getline, but raises an exception of end-of-file.

  • readlines

    Returns an array of all lines read read from self.

  • readpartial

    Returns up to the given number of bytes from self.

Writing

  • ::binwrite

    Writes the given string to the file at the given filepath, in binary mode.

  • ::write

    Writes the given string to self.

  • :<<

    Appends the given string to self.

  • print

    Prints last read line or given objects to self.

  • printf

    Writes to self based on the given format string and objects.

  • putc

    Writes a character to self.

  • puts

    Writes lines to self, making sure line ends with a newline.

  • pwrite

    Writes the given string at the given offset, not updating the receiver's offset.

  • write

    Writes one or more given strings to self.

  • write_nonblock

    Writes one or more given strings to self in non-blocking mode.

Positioning

  • lineno

    Returns the current line number in self.

  • lineno=

    Sets the line number is self.

  • pos (aliased as tell)

    Returns the current byte offset in self.

  • pos=

    Sets the byte offset in self.

  • reopen

    Reassociates self with a new or existing IO stream.

  • rewind

    Positions self to the beginning of input.

  • seek

    Sets the offset for self relative to given position.

Iterating

  • ::foreach

    Yields each line of given file to the block.

  • each (aliased as each_line)

    Calls the given block with each successive line in self.

  • each_byte

    Calls the given block with each successive byte in self as an integer.

  • each_char

    Calls the given block with each successive character in self as a string.

  • each_codepoint

    Calls the given block with each successive codepoint in self as an integer.

Settings

Querying

  • autoclose?

    Returns whether self auto-closes.

  • binmode?

    Returns whether self is in binary mode.

  • close_on_exec?

    Returns the close-on-exec flag for self.

  • closed?

    Returns whether self is closed.

  • eof? (aliased as eof)

    Returns whether self is at end-of-file.

  • external_encoding

    Returns the external encoding object for self.

  • fileno (aliased as to_i)

    Returns the integer file descriptor for self

  • internal_encoding

    Returns the internal encoding object for self.

  • pid

    Returns the process ID of a child process associated with self, if self was created by ::popen.

  • stat

    Returns the File::Stat object containing status information for self.

  • sync

    Returns whether self is in sync-mode.

  • tty (aliased as isatty)

    Returns whether self is a terminal.

Buffering

  • fdatasync

    Immediately writes all buffered data in self to disk.

  • flush

    Flushes any buffered data within self to the underlying operating system.

  • fsync

    Immediately writes all buffered data and attributes in self to disk.

  • ungetbyte

    Prepends buffer for self with given integer byte or string.

  • ungetc

    Prepends buffer for self with given string.

Low-Level Access

  • ::sysopen

    Opens the file given by its path, returning the integer file descriptor.

  • advise

    Announces the intention to access data from self in a specific way.

  • fcntl

    Passes a low-level command to the file specified by the given file descriptor.

  • ioctl

    Passes a low-level command to the device specified by the given file descriptor.

  • sysread

    Returns up to the next n bytes read from self using a low-level read.

  • sysseek

    Sets the offset for self.

  • syswrite

    Writes the given string to self using a low-level write.

Other

  • ::copy_stream

    Copies data from a source to a destination, each of which is a filepath or an IO-like object.

  • ::try_convert

    Returns a new IO object resulting from converting the given object.

  • inspect

    Returns the string representation of self.


Constants


No documentation available
No documentation available

Set I/O position from the current position

Set I/O position to the next location containing data

Set I/O position from the end

Set I/O position to the next hole

Set I/O position from the beginning

No documentation available

Class Methods


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".

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is returned. Consider to use File.binread to disable the behavior of subprocess invocation.

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

See also IO.read for details about name and open_args.

Same as IO.write except opening the file in binary mode and ASCII-8BIT encoding ("wb:ASCII-8BIT").

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is printed to the standard output. Consider to use File.binwrite to disable the behavior of subprocess invocation.

See also IO.read for details about name and open_args.

Returns an File instance opened console.

If sym is given, it will be sent to the opened console with args and the result will be returned instead of the console IO itself.

You must require 'io/console' to use this method.

IO.copy_stream copies src to dst. src and dst is either a filename or an IO-like object. IO-like object for src should have readpartial or read method. IO-like object for dst should have write method. (Specialized mechanisms, such as sendfile system call, may be used on appropriate situation.)

This method returns the number of bytes copied.

If optional arguments are not given, the start position of the copy is the beginning of the filename or the current file offset of the IO. The end position of the copy is the end of file.

If copy_length is given, No more than copy_length bytes are copied.

If src_offset is given, it specifies the start position of the copy.

When src_offset is specified and src is an IO, IO.copy_stream doesn't move the current file offset.

fallback to console window size

Synonym for IO.new.

Executes the block for every line in the named I/O port, where lines are separated by sep.

If no block is given, an enumerator is returned instead.

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and each line in its output is yielded. Consider to use File.foreach to disable the behavior of subprocess invocation.

File.foreach("testfile") {|x| print "GOT ", x }
IO.foreach("| cat testfile") {|x| print "GOT ", x }

produces:

GOT This is line one
GOT This is line two
GOT This is line three
GOT And so on...

If the last argument is a hash, it's the keyword argument to open. See IO.readlines for details about getline_args. And see also IO.read for details about open_args.

Returns a new IO object (a stream) for the given integer file descriptor fd and mode string. opt may be used to specify parts of mode in a more readable fashion. See also IO.sysopen and IO.for_fd.

IO.new is called by various File and IO opening methods such as IO::open, Kernel#open, and File::open.

Open Mode

When mode is an integer it must be combination of the modes defined in File::Constants (File::RDONLY, File::WRONLY|File::CREAT). See the open(2) man page for more information.

When mode is a string it must be in one of the following forms:

fmode
fmode ":" ext_enc
fmode ":" ext_enc ":" int_enc
fmode ":" "BOM|UTF-*"

fmode is an IO open mode string, ext_enc is the external encoding for the IO and int_enc is the internal encoding.

IO Open Mode

Ruby allows the following open modes:

"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.

"b"  Binary file mode
     Suppresses EOL <-> CRLF conversion on Windows. And
     sets external encoding to ASCII-8BIT unless explicitly
     specified.

"t"  Text file mode

The exclusive access mode (“x”) can be used together with “w” to ensure the file is created. Errno::EEXIST is raised when it already exists. It may not be supported with all kinds of streams (e.g. pipes).

When the open mode of original IO is read only, the mode cannot be changed to be writable. Similarly, the open mode cannot be changed from write only to readable.

When such a change is attempted the error is raised in different locations according to the platform.

IO Encoding

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.)

Options

opt can be used instead of mode for improved readability. The following keys are supported:

:mode

Same as mode parameter

:flags

Specifies file open flags as integer. If mode parameter is given, this parameter will be bitwise-ORed.

:external_encoding

External encoding for the IO.

:internal_encoding

Internal encoding for the IO. “-” is a synonym for the default internal encoding.

If the value is nil no conversion occurs.

:encoding

Specifies external and internal encodings as “extern:intern”.

:textmode

If the value is truth value, same as “t” in argument mode.

:binmode

If the value is truth value, same as “b” in argument mode.

:autoclose

If the value is false, the fd will be kept open after this IO instance gets finalized.

Also, opt can have same keys in String#encode for controlling conversion between the external encoding and the internal encoding.

Example 1

fd = IO.sysopen("/dev/tty", "w")
a = IO.new(fd,"w")
$stderr.puts "Hello"
a.puts "World"

Produces:

Hello
World

Example 2

require 'fcntl'

fd = STDERR.fcntl(Fcntl::F_DUPFD)
io = IO.new(fd, mode: 'w:UTF-16LE', cr_newline: true)
io.puts "Hello, World!"

fd = STDERR.fcntl(Fcntl::F_DUPFD)
io = IO.new(fd, mode: 'w', cr_newline: true,
            external_encoding: Encoding::UTF_16LE)
io.puts "Hello, World!"

Both of above print “Hello, World!” in UTF-16LE to standard error output with converting EOL generated by puts to CR.

Creates a new IO object, via IO.new with the given arguments.

With no block given, returns the IO object.

With a block given, calls the block with the IO object and returns the block's value.

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.

rd, wr = IO.pipe

if fork
  wr.close
  puts "Parent got: <#{rd.read}>"
  rd.close
  Process.wait
else
  rd.close
  puts "Sending message to parent"
  wr.write "Hi Dad"
  wr.close
end

produces:

Sending message to parent
Parent got: <Hi Dad>

Executes the given command cmd as a subprocess whose $stdin and $stdout are connected to a new stream io.

If no block is given, returns the new stream, which depending on given mode may be open for reading, writing, or both. The stream should be explicitly closed (eventually) to avoid resource leaks.

If a block is given, the stream is passed to the block (again, open for reading, writing, or both); when the block exits, the stream is closed, and the block's value is assigned to global variable $? and returned.

Optional argument mode may be any valid IO mode. See Modes.

Required argument cmd determines which of the following occurs:

  • The process forks.

  • A specified program runs in a shell.

  • A specified program runs with specified arguments.

  • A specified program runs with specified arguments and a specified argv0.

Each of these is detailed below.

The optional hash argument env specifies name/value pairs that are to be added to the environment variables for the subprocess:

IO.popen({'FOO' => 'bar'}, 'ruby', 'r+') do |pipe|
  pipe.puts 'puts ENV["FOO"]'
  pipe.close_write
  pipe.gets
end => "bar\n"

The optional keyword arguments opts may be IO open options and options for Kernel#spawn.

Forked Process

When argument cmd is the 1-character string '-', causes the process to fork:

IO.popen('-') do |pipe|
  if pipe
    $stderr.puts "In parent, child pid is #{pipe.pid}\n"
  else
    $stderr.puts "In child, pid is #{$$}\n"
  end
end

Output:

In parent, child pid is 26253
In child, pid is 26253

Note that this is not supported on all platforms.

Shell Subprocess

When argument cmd is a single string (but not '-'), the program named cmd is run as a shell command:

IO.popen('uname') do |pipe|
  pipe.readlines
end

Output:

["Linux\n"]

Another example:

IO.popen('/bin/sh', 'r+') do |pipe|
  pipe.puts('ls')
  pipe.close_write
  $stderr.puts pipe.readlines.size
end

Output:

213

Program Subprocess

When argument cmd is an array of strings, the program named cmd[0] is run with all elements of cmd as its arguments:

IO.popen(['du', '..', '.']) do |pipe|
  $stderr.puts pipe.readlines.size
end

Output:

1111

Program Subprocess with argv0

When argument cmd is an array whose first element is a 2-element string array and whose remaining elements (if any) are strings:

  • cmd[0][0] (the first string in the nested array) is the name of a program that is run.

  • cmd[0][1] (the second string in the nested array) is set as the program's argv[0].

  • <tt>cmd (the strings in the outer array) are the program's arguments.

Example (sets $0 to 'foo'):

IO.popen([['/bin/sh', 'foo'], '-c', 'echo $0']).read # => "foo\n"

Some Special Examples

# Set IO encoding.
IO.popen("nkf -e filename", :external_encoding=>"EUC-JP") {|nkf_io|
  euc_jp_string = nkf_io.read
}

# Merge standard output and standard error using Kernel#spawn option. See Kernel#spawn.
IO.popen(["ls", "/", :err=>[:child, :out]]) do |io|
  ls_result_with_error = io.read
end

# Use mixture of spawn options and IO options.
IO.popen(["ls", "/"], :err=>[:child, :out]) do |io|
  ls_result_with_error = io.read
end

 f = IO.popen("uname")
 p f.readlines
 f.close
 puts "Parent is #{Process.pid}"
 IO.popen("date") {|f| puts f.gets }
 IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f.inspect}"}
 p $?
 IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f|
   f.puts "bar"; f.close_write; puts f.gets
 }

Output (from last section):

["Linux\n"]
Parent is 21346
Thu Jan 15 22:41:19 JST 2009
21346 is here, f is #<IO:fd 3>
21352 is here, f is nil
#<Process::Status: pid 21352 exit 0>
<foo>bar;zot;

Raises exceptions that IO.pipe and Kernel.spawn raise.

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 ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is returned. Consider to use File.read to disable the behavior of subprocess invocation.

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:

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

Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep.

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and each line in its output is yielded. Consider to use File.readlines to disable the behavior of subprocess invocation.

a = File.readlines("testfile")
a[0]   #=> "This is line one\n"

b = File.readlines("testfile", chomp: true)
b[0]   #=> "This is line one"

IO.readlines("|ls -a")     #=> [".\n", "..\n", ...]

If the last argument is a hash, it's the keyword argument to open.

Options for getline

The options hash accepts the following keys:

:chomp

When the optional chomp keyword argument has a true value, \n, \r, and \r\n will be removed from the end of each line.

See also IO.read for details about name and open_args.

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:

begin
  result = io_like.read_nonblock(maxlen)
rescue IO::WaitReadable
  IO.select([io_like])
  retry
rescue IO::WaitWritable
  IO.select(nil, [io_like])
  retry
end

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 block.

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 are 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.

while 0 < string.bytesize
  begin
    written = io_like.write_nonblock(string)
  rescue IO::WaitReadable
    IO.select([io_like])
    retry
  rescue IO::WaitWritable
    IO.select(nil, [io_like])
    retry
  end
  string = string.byteslice(written..-1)
end

Parameters

read_array

an array of IO objects that wait until ready for read

write_array

an array of IO objects that wait until ready for write

error_array

an array of IO objects that wait for exceptions

timeout

a numeric value in second

Example

rp, wp = IO.pipe
mesg = "ping "
100.times {
  # IO.select follows IO#read.  Not the best way to use IO.select.
  rs, ws, = IO.select([rp], [wp])
  if r = rs[0]
    ret = r.read(5)
    print ret
    case ret
    when /ping/
      mesg = "pong\n"
    when /pong/
      mesg = "ping "
    end
  end
  if w = ws[0]
    w.write(mesg)
  end
}

produces:

ping pong
ping pong
ping pong
(snipped)
ping

Opens the file at the given path with the given mode and permissions; returns the integer file descriptor.

If the file is to be readable, it must exist; if the file is to be writable and does not exist, it is created with the given permissions:

File.write('t.tmp', '')  # => 0
IO.sysopen('t.tmp')      # => 8
IO.sysopen('t.tmp', 'w') # => 9

Attempts to convert object into an IO object via method to_io; returns the new IO object if successful, or nil otherwise:

IO.try_convert(STDOUT)   # => #<IO:<STDOUT>>
IO.try_convert(ARGF)     # => #<IO:<STDIN>>
IO.try_convert('STDOUT') # => nil

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 in write mode, the file is truncated. Otherwise, it is not truncated.

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is printed to the standard output. Consider to use File.write to disable the behavior of subprocess invocation.

File.write("testfile", "0123456789", 20)  #=> 10
# File could contain:  "This is line one\nThi0123456789two\nThis is line three\nAnd so on...\n"
File.write("testfile", "0123456789")      #=> 10
# File would now read: "0123456789"
IO.write("|tr a-z A-Z", "abc")            #=> 3
# Prints "ABC" to the standard output

If the last argument is a hash, it specifies options for the internal open(). It accepts the following keys:

:encoding

string or encoding

Specifies the encoding of the read string. See Encoding.aliases for possible encodings.

:mode

string or integer

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

:perm

integer

Specifies the perm argument for open().

:open_args

array

Specifies arguments for open() as an array. This key can not be used in combination with other keys.

See also IO.read for details about name and open_args.

Instance Methods


Writes the given object to self, which must be opened for writing (see Modes); returns self; if object is not a string, it is converted via method to_s:

$stdout << 'Hello' << ', ' << 'World!' << "\n"
$stdout << 'foo' << :bar << 2 << "\n"

Output:

Hello, World!
foobar2

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.

RangeError

One of the arguments given was too big/small.

This list is not exhaustive; other Errno

exceptions are also possible.

Sets auto-close flag.

f = open("/dev/null")
IO.for_fd(f.fileno)
# ...
f.gets # may cause Errno::EBADF

f = open("/dev/null")
IO.for_fd(f.fileno).autoclose = false
# ...
f.gets # won't cause Errno::EBADF

Returns true if the underlying file descriptor of ios will be closed automatically at its finalization, otherwise false.

No documentation available

Sets the stream's data mode as binary (see Data Mode).

A stream's data mode may not be changed from binary to text.

Returns true if the stream is on binary mode, false otherwise. See Data Mode.

No documentation available
No documentation available

Closes the stream, if it is open, after flushing any buffered writes to the operating system; does nothing if the stream is already closed. A stream is automatically closed when claimed by the garbage collector.

If the stream was opened by IO.popen, close sets global variable $?.

Sets a close-on-exec flag.

f = open("/dev/null")
f.close_on_exec = true
system("cat", "/proc/self/fd/#{f.fileno}") # cat: /proc/self/fd/3: No such file or directory
f.closed?                #=> false

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.

Returns true if the stream will be closed on exec, false otherwise:

f = File.open('t.txt')
f.close_on_exec? # => true
f.close_on_exec = false
f.close_on_exec? # => false

Closes the read end of a duplexed stream (i.e., one that is both readable and writable, such as a pipe); does nothing if already closed:

f = IO.popen('/bin/sh','r+')
f.close_read
f.readlines # Raises IOError

Raises an exception if the stream is not duplexed.

Closes the write end of a duplexed stream (i.e., one that is both readable and writable, such as a pipe); does nothing if already closed:

f = IO.popen('/bin/sh', 'r+')
f.close_write
f.print 'nowhere' # Raises IOError.

Returns true if the stream is closed for both reading and writing, false otherwise:

f = File.new('t.txt')
f.close        # => nil
f.closed?      # => true
f = IO.popen('/bin/sh','r+')
f.close_write  # => nil
f.closed?      # => false
f.close_read   # => nil
f.closed?      # => true

Returns a data represents the current console mode.

You must require 'io/console' to use this method.

Sets the console mode to mode.

You must require 'io/console' to use this method.

Yields self within cooked mode.

STDIN.cooked(&:gets)

will read and return a line with echo back and line editing.

You must require 'io/console' to use this method.

Enables cooked mode.

If the terminal mode needs to be back, use io.cooked { … }.

You must require 'io/console' to use this method.

No documentation available
No documentation available
No documentation available
No documentation available
No documentation available
No documentation available

Calls the block with each remaining line read from the stream; does nothing if already at end-of-file; returns self.

With no arguments given, reads lines as determined by line separator $/:

f = File.new('t.txt')
f.each_line {|line| p line }
f.each_line {|line| fail 'Cannot happen' }

Output:

"First line\n"
"Second line\n"
"\n"
"Fourth line\n"
"Fifth line\n"

With only string argument sep given, reads lines as determined by line separator sep; see Line Separator:

f = File.new('t.txt')
f.each_line('li') {|line| p line }

Output:

"First li"
"ne\nSecond li"
"ne\n\nFourth li"
"ne\nFifth li"
"ne\n"

The two special values for sep are honored:

f = File.new('t.txt')
# Get all into one string.
f.each_line(nil) {|line| p line }

Output:

"First line\nSecond line\n\nFourth line\nFifth line\n"

f.rewind
# Get paragraphs (up to two line separators).
f.each_line('') {|line| p line }

Output:

"First line\nSecond line\n\n"
"Fourth line\nFifth line\n"

With only integer argument limit given, limits the number of bytes in each line; see Line Limit}:

f = File.new('t.txt')
f.each_line(8) {|line| p line }

Output:

"First li"
"ne\n"
"Second l"
"ine\n"
"\n"
"Fourth l"
"ine\n"
"Fifth li"
"ne\n"

With arguments sep and limit given, combines the two behaviors:

  • Calls with the next line as determined by line separator sep.

  • But returns no more bytes than are allowed by the limit.

For all forms above, trailing optional keyword arguments may be given; see Line Options:

f = File.new('t.txt')
f.each_line(chomp: true) {|line| p line }

Output:

"First line"
"Second line"
""
"Fourth line"
"Fifth line"

Returns an Enumerator if no block is given.

IO#each is an alias for IO#each_line.

Calls the given block with each byte (0..255) in the stream; returns self:

f = File.new('t.rus')
a = []
f.each_byte {|b| a << b }
a # => [209, 130, 208, 181, 209, 129, 209, 130]

Returns an Enumerator if no block is given.

Related: IO#each_char, IO#each_codepoint.

Calls the given block with each character in the stream; returns self:

f = File.new('t.rus')
a = []
f.each_char {|c| a << c.ord }
a # => [1090, 1077, 1089, 1090]

Returns an Enumerator if no block is given.

Related: IO#each_byte, IO#each_codepoint.

Calls the given block with each codepoint in the stream; returns self:

f = File.new('t.rus')
a = []
f.each_codepoint {|c| a << c }
a # => [1090, 1077, 1089, 1090]

Returns an Enumerator if no block is given.

Related: IO#each_byte, IO#each_char.

Enables/disables echo back. On some platforms, all combinations of this flags and raw/cooked mode may not be valid.

You must require 'io/console' to use this method.

Returns true if echo back is enabled.

You must require 'io/console' to use this method.

Returns true if the stream is positioned at its end, false otherwise; see Position:

f = File.open('t.txt')
f.eof           # => false
f.seek(0, :END) # => 0
f.eof           # => true

Raises an exception unless the stream is opened for reading; see Mode.

If self is a stream such as pipe or socket, this method blocks until the other end sends some data or closes it:

r, w = IO.pipe
Thread.new { sleep 1; w.close }
r.eof? # => true # After 1-second wait.

r, w = IO.pipe
Thread.new { sleep 1; w.puts "a" }
r.eof?  # => false # After 1-second wait.

r, w = IO.pipe
r.eof?  # blocks forever

Note that this method reads data to the input byte buffer. So IO#sysread may not behave as you intend with IO#eof?, unless you call IO#rewind first (which is not available for some streams).

I#eof? is an alias for IO#eof.

An alias for eof
No documentation available
No documentation available

Reads from the IO until the given pattern matches or the timeout is over.

It returns an array with the read buffer, followed by the matches. If a block is given, the result is yielded to the block and returns nil.

When called without a block, it waits until the input that matches the given pattern is obtained from the IO or the time specified as the timeout passes. An array is returned when the pattern is obtained from the IO. The first element of the array is the entire string obtained from the IO until the pattern matches, followed by elements indicating which the pattern which matched to the anchor in the regular expression.

The optional timeout parameter defines, in seconds, the total time to wait for the pattern. If the timeout expires or eof is found, nil is returned or yielded. However, the buffer in a timeout session is kept for the next expect call. The default timeout is 9999999 seconds.

Returns the Encoding object that represents the encoding of the file. If io is in write mode and no encoding is specified, returns nil.

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.

Immediately writes to disk all data buffered in the stream, via the operating system's: fdatasync(2), if supported, otherwise via fsync(2), if supported; otherwise raises an exception.

Returns the integer file descriptor for the stream:

$stdin.fileno             # => 0
$stdout.fileno            # => 1
$stderr.fileno            # => 2
File.open('t.txt').fileno # => 10

IO#to_i is an alias for IO#fileno.

Flushes data buffered in self to the operating system (but does not necessarily flush data buffered in the operating system):

$stdout.print 'no newline' # Not necessarily flushed.
$stdout.flush              # Flushed.

Immediately writes to disk all data buffered in the stream, via the operating system's fsync(2).

Note this difference:

  • IO#sync=: Ensures that data is flushed from the stream's internal buffers, but does not guarantee that the operating system actually writes the data to disk.

  • IO#fsync: Ensures both that data is flushed from internal buffers, and that data is written to disk.

Raises an exception if the operating system does not support fsync(2).

Reads and returns the next byte (in range 0..255) from the stream; returns nil if already at end-of-file:

f = File.open('t.txt')
f.getbyte # => 70
f = File.open('t.rus')
f.getbyte # => 209

Related: IO#readbyte (may raise EOFError).

Reads and returns the next 1-character string from the stream; returns nil if already at end-of-file:

f = File.open('t.txt')
f.getc     # => "F"
f = File.open('t.rus')
f.getc.ord # => 1090

Related: IO#readchar (may raise EOFError).

Reads and returns a character in raw mode.

See IO#raw for details on the parameters.

You must require 'io/console' to use this method.

Reads and returns a line without echo back. Prints prompt unless it is nil.

The newline character that terminates the read line is removed from the returned string, see String#chomp!.

You must require 'io/console' to use this method.

Reads and returns a line from the stream (see Lines) assigns the return value to $_.

With no arguments given, returns the next line as determined by line separator $/, or nil if none:

f = File.open('t.txt')
f.gets # => "First line\n"
$_     # => "First line\n"
f.gets # => "\n"
f.gets # => "Fourth line\n"
f.gets # => "Fifth line\n"
f.gets # => nil

With only string argument sep given, returns the next line as determined by line separator sep, or nil if none; see Line Separator:

f = File.new('t.txt')
f.gets('l')   # => "First l"
f.gets('li')  # => "ine\nSecond li"
f.gets('lin') # => "ne\n\nFourth lin"
f.gets        # => "e\n"

The two special values for sep are honored:

f = File.new('t.txt')
# Get all.
f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.rewind
# Get paragraph (up to two line separators).
f.gets('')  # => "First line\nSecond line\n\n"

With only integer argument limit given, limits the number of bytes in the line; see Line Limit}:

# No more than one line.
File.open('t.txt') {|f| f.gets(10) } # => "First line"
File.open('t.txt') {|f| f.gets(11) } # => "First line\n"
File.open('t.txt') {|f| f.gets(12) } # => "First line\n"

With arguments sep and limit given, combines the two behaviors:

  • Returns the next line as determined by line separator sep, or nil if none.

  • But returns no more bytes than are allowed by the limit.

For all forms above, trailing optional keyword arguments may be given; see Line Options:

f = File.open('t.txt')
# Chomp the lines.
f.gets(chomp: true) # => "First line"
f.gets(chomp: true) # => "Second line"
f.gets(chomp: true) # => ""
f.gets(chomp: true) # => "Fourth line"
f.gets(chomp: true) # => "Fifth line"
f.gets(chomp: true) # => nil
No documentation available
No documentation available

Flushes input buffer in kernel.

You must require 'io/console' to use this method.

Returns a string representation of self:

f = File.open('t.txt')
f.inspect # => "#<File:t.txt>"

Returns the Encoding of the internal string if conversion is specified. Otherwise returns nil.

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.

Flushes input and output buffers in kernel.

You must require 'io/console' to use this method.

Returns true if the stream is associated with a terminal device (tty), false otherwise:

File.new('t.txt').isatty    #=> false
File.new('/dev/tty').isatty #=> true

IO#tty? is an alias for IO#isatty.

Returns the current line number for the stream. See Line Number.

Sets and returns the line number for the stream. See Line Number.

Yields self with disabling echo back.

STDIN.noecho(&:gets)

will read and return a line without echo back.

You must require 'io/console' to use this method.

Yields self in non-blocking mode.

When false is given as an argument, self is yielded in blocking mode. The original mode is restored after the block is executed.

Enables non-blocking mode on a stream when set to true, and blocking mode when set to false.

Returns true if an IO object is in non-blocking mode.

Returns number of bytes that can be read without blocking. Returns zero if no information available.

Flushes output buffer in kernel.

You must require 'io/console' to use this method.

Returns pathname configuration variable using fpathconf().

name should be a constant under Etc which begins with PC_.

The return value is an integer or nil. nil means indefinite limit. (fpathconf() returns -1 but errno is not set.)

require 'etc'
IO.pipe {|r, w|
  p w.pathconf(Etc::PC_PIPE_BUF) #=> 4096
}

Returns the process ID of a child process associated with the stream, which will have been set by IO#popen, or nil if the stream was not created by IO#popen:

pipe = IO.popen("-")
if pipe
  $stderr.puts "In parent, child pid is #{pipe.pid}"
else
  $stderr.puts "In child, pid is #{$$}"
end

Output:

In child, pid is 26209
In parent, child pid is 26209
An alias for tell

Seeks to the given new_position (in bytes); see Position:

f = File.open('t.txt')
f.tell     # => 0
f.pos = 20 # => 20
f.tell     # => 20

Related: IO#seek, IO#tell.

Behaves like IO#readpartial, except that it:

  • Reads at the given offset (in bytes).

  • Disregards, and does not modify, the stream's position (see Position).

  • Bypasses any user space buffering in the stream.

Because this method does not disturb the stream's state (its position, in particular), pread allows multiple threads and processes to use the same IO object for reading at various offsets.

f = File.open('t.txt')
f.read # => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.pos  # => 52
# Read 12 bytes at offset 0.
f.pread(12, 0) # => "First line\n"
# Read 9 bytes at offset 8.
f.pread(9, 8)  # => "ne\nSecon"

Not available on some platforms.

No documentation available

Writes the given object(s) to ios. Returns nil.

The stream must be opened for writing. Each given object that isn't a string will be converted by calling its to_s method. When called without arguments, prints the contents of $_.

If the output field separator ($,) is not nil, it is inserted between objects. If the output record separator ($\) is not nil, it is appended to the output.

$stdout.print("This is ", 100, " percent.\n")

produces:

This is 100 percent.

Formats and writes to ios, converting parameters under control of the format string. See Kernel#sprintf for details.

If obj is Numeric, write the character whose code is the least-significant byte of obj. If obj is String, write the first character of obj to ios. Otherwise, raise TypeError.

$stdout.putc "A"
$stdout.putc 65

produces:

AA

Writes the given objects to the stream, which must be open for writing; returns nil.\ Writes a newline after each that does not already end with a newline sequence. If called without arguments, writes a newline.

Note that each added newline is the character "\n"<//tt>, not the output record separator (<tt>$\).

Treatment for each object:

  • String: writes the string.

  • Neither string nor array: writes object.to_s.

  • Array: writes each element of the array; arrays may be nested.

To keep these examples brief, we define this helper method:

def show(*objects)
  # Puts objects to file.
  f = File.new('t.tmp', 'w+')
  f.puts(objects)
  # Return file content.
  f.rewind
  p f.read
end

# Strings without newlines.
show('foo', 'bar', 'baz')     # => "foo\nbar\nbaz\n"
# Strings, some with newlines.
show("foo\n", 'bar', "baz\n") # => "foo\nbar\nbaz\n"

# Neither strings nor arrays:
show(0, 0.0, Rational(0, 1), Complex(9, 0), :zero)
# => "0\n0.0\n0/1\n9+0i\nzero\n"

# Array of strings.
show(['foo', "bar\n", 'baz']) # => "foo\nbar\nbaz\n"
# Nested arrays.
show([[[0, 1], 2, 3], 4, 5])  # => "0\n1\n2\n3\n4\n5\n"

Behaves like IO#write, except that it:

  • Writes at the given offset (in bytes).

  • Disregards, and does not modify, the stream's position (see Position).

  • Bypasses any user space buffering in the stream.

Because this method does not disturb the stream's state (its position, in particular), pwrite allows multiple threads and processes to use the same IO object for writing at various offsets.

f = File.open('t.tmp', 'w+')
# Write 6 bytes at offset 3.
f.pwrite('ABCDEF', 3) # => 6
f.rewind
f.read # => "\u0000\u0000\u0000ABCDEF"

Not available on some platforms.

Yields self within raw mode, and returns the result of the block.

STDIN.raw(&:gets)

will read and return a line without echo back and line editing.

The parameter min specifies the minimum number of bytes that should be received when a read operation is performed. (default: 1)

The parameter time specifies the timeout in seconds with a precision of 1/10 of a second. (default: 0)

If the parameter intr is true, enables break, interrupt, quit, and suspend special characters.

Refer to the manual page of termios for further details.

You must require 'io/console' to use this method.

Enables raw mode, and returns io.

If the terminal mode needs to be back, use io.raw { ... }.

See IO#raw for details on the parameters.

You must require 'io/console' to use this method.

Reads bytes from the stream (in binary mode):

  • If maxlen is nil, reads all bytes.

  • Otherwise reads maxlen bytes, if available.

  • Otherwise reads all bytes.

Returns a string (either a new string or the given out_string) containing the bytes read. The encoding of the string depends on both maxLen and out_string:

  • maxlen is nil: uses internal encoding of self (regardless of whether out_string was given).

  • maxlen not nil:

    • out_string given: encoding of out_string not modified.

    • out_string not given: ASCII-8BIT is used.

Without Argument out_string

When argument out_string is omitted, the returned value is a new string:

f = File.new('t.txt')
f.read
# => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.rewind
f.read(30) # => "First line\r\nSecond line\r\n\r\nFou"
f.read(30) # => "rth line\r\nFifth line\r\n"
f.read(30) # => nil

If maxlen is zero, returns an empty string.

With Argument out_string

When argument out_string is given, the returned value is out_string, whose content is replaced:

f = File.new('t.txt')
s = 'foo'      # => "foo"
f.read(nil, s) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
s              # => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.rewind
s = 'bar'
f.read(30, s)  # => "First line\r\nSecond line\r\n\r\nFou"
s              # => "First line\r\nSecond line\r\n\r\nFou"
s = 'baz'
f.read(30, s)  # => "rth line\r\nFifth line\r\n"
s              # => "rth line\r\nFifth line\r\n"
s = 'bat'
f.read(30, s)  # => nil
s              # => ""

Note that this method behaves like the fread() function in C. This means it retries to invoke read(2) system calls to read data with the specified maxlen (or until EOF).

This behavior is preserved even if the stream is in non-blocking mode. (This method is non-blocking-flag insensitive as other methods.)

If you need the behavior like a 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.

read_nonblock causes EOFError on EOF.

On some platforms, such as Windows, non-blocking mode is not supported on IO objects other than sockets. In such cases, Errno::EBADF will be raised.

If the read byte buffer is not empty, read_nonblock reads from the buffer like readpartial. In this case, the read(2) system call is not called.

When read_nonblock raises an exception kind of IO::WaitReadable, read_nonblock should not be called until io is readable for avoiding busy loop. This can be done as follows.

# emulates blocking read (readpartial).
begin
  result = io.read_nonblock(maxlen)
rescue IO::WaitReadable
  IO.select([io])
  retry
end

Although IO#read_nonblock doesn't raise IO::WaitWritable. OpenSSL::Buffering#read_nonblock can raise IO::WaitWritable. If IO and SSL should be used polymorphically, IO::WaitWritable should be rescued too. See the document of OpenSSL::Buffering#read_nonblock for sample code.

Note that this method is identical to readpartial except the non-blocking flag is set.

By specifying a keyword argument exception to false, you can indicate that read_nonblock should not raise an IO::WaitReadable exception, but return the symbol :wait_readable instead. At EOF, it will return nil instead of raising EOFError.

Reads and returns the next byte (in range 0..255) from the stream; raises EOFError if already at end-of-file:

f = File.open('t.txt')
f.readbyte # => 70
f = File.open('t.rus')
f.readbyte # => 209

Related: IO#getbyte (will not raise EOFError).

Reads and returns the next 1-character string from the stream; raises EOFError if already at end-of-file:

f = File.open('t.txt')
f.readchar     # => "F"
f = File.open('t.rus')
f.readchar.ord # => 1090

Related: IO#getc (will not raise EOFError).

Reads a line as with IO#gets, but raises EOFError if already at end-of-file.

Reads and returns all remaining line from the stream (see Lines); does not modify $_.

With no arguments given, returns lines as determined by line separator $/, or nil if none:

f = File.new('t.txt')
f.readlines
# => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
f.readlines # => []

With only string argument sep given, returns lines as determined by line separator sep, or nil if none; see Line Separator:

f = File.new('t.txt')
f.readlines('li')
# => ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]

The two special values for sep are honored:

f = File.new('t.txt')
# Get all into one string.
f.readlines(nil)
# => ["First line\nSecond line\n\nFourth line\nFifth line\n"]
# Get paragraphs (up to two line separators).
f.rewind
f.readlines('')
# => ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]

With only integer argument limit given, limits the number of bytes in each line; see Line Limit}:

f = File.new('t.txt')
f.readlines(8)
# => ["First li", "ne\n", "Second l", "ine\n", "\n", "Fourth l", "ine\n", "Fifth li", "ne\n"]

With arguments sep and limit given, combines the two behaviors:

  • Returns lines as determined by line separator sep.

  • But returns no more bytes in a line than are allowed by the limit.

For all forms above, trailing optional keyword arguments may be given; see Line Options:

f = File.new('t.txt')
f.readlines(chomp: true)
# => ["First line", "Second line", "", "Fourth line", "Fifth line"]

Reads up to maxlen bytes from the stream; returns a string (either a new string or the given out_string). Its encoding is:

  • The unchanged encoding of out_string, if out_string is given.

  • ASCII-8BIT, otherwise.

  • Contains maxlen bytes from the stream, if available.

  • Otherwise contains all available bytes, if any available.

  • Otherwise is an empty string.

With the single non-negative integer argument maxlen given, returns a new string:

f = File.new('t.txt')
f.readpartial(20) # => "First line\nSecond l"
f.readpartial(20) # => "ine\n\nFourth line\n"
f.readpartial(20) # => "Fifth line\n"
f.readpartial(20) # Raises EOFError.

With both argument maxlen and string argument out_string given, returns modified out_string:

f = File.new('t.txt')
s = 'foo'
f.readpartial(20, s) # => "First line\nSecond l"
s = 'bar'
f.readpartial(0, s)  # => ""

This method is useful for a stream such as a pipe, a socket, or a tty. It blocks only when no data is immediately available. This means that it blocks only when all of the following are true:

  • The byte buffer in the stream is empty.

  • The content of the stream is empty.

  • The stream is not at EOF.

When blocked, the method waits for either more data or EOF on the stream:

  • If more data is read, the method returns the data.

  • If EOF is reached, the method raises EOFError.

When not blocked, the method responds immediately:

  • Returns data from the buffer if there is any.

  • Otherwise returns data from the stream if there is any.

  • Otherwise raises EOFError if the stream has reached EOF.

Note that this method is similar to sysread. The differences are:

  • If the byte buffer is not empty, read from the byte buffer instead of “sysread for buffered IO (IOError)”.

  • It doesn't cause Errno::EWOULDBLOCK and Errno::EINTR. When readpartial meets EWOULDBLOCK and EINTR by read system call, readpartial retries the system call.

The latter means that readpartial is non-blocking-flag insensitive. It blocks on the situation IO#sysread causes Errno::EWOULDBLOCK as if the fd is blocking mode.

Examples:

#                        # Returned      Buffer Content    Pipe Content
r, w = IO.pipe           #
w << 'abc'               #               ""                "abc".
r.readpartial(4096)      # => "abc"      ""                ""
r.readpartial(4096)      # (Blocks because buffer and pipe are empty.)

#                        # Returned      Buffer Content    Pipe Content
r, w = IO.pipe           #
w << 'abc'               #               ""                "abc"
w.close                  #               ""                "abc" EOF
r.readpartial(4096)      # => "abc"      ""                 EOF
r.readpartial(4096)      # raises EOFError

#                        # Returned      Buffer Content    Pipe Content
r, w = IO.pipe           #
w << "abc\ndef\n"        #               ""                "abc\ndef\n"
r.gets                   # => "abc\n"    "def\n"           ""
w << "ghi\n"             #               "def\n"           "ghi\n"
r.readpartial(4096)      # => "def\n"    ""                "ghi\n"
r.readpartial(4096)      # => "ghi\n"    ""                ""

Returns true if input available without blocking, or false.

Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path. This may dynamically change the actual class of this stream. The mode and opt parameters accept the same values as IO.open.

f1 = File.new("testfile")
f2 = File.new("testfile")
f2.readlines[0]   #=> "This is line one\n"
f2.reopen(f1)     #=> #<File:testfile>
f2.readlines[0]   #=> "This is line one\n"

Repositions the stream to its beginning, setting both the position and the line number to zero; see Position and Line Number:

f = File.open('t.txt')
f.tell     # => 0
f.lineno   # => 0
f.gets     # => "First line\n"
f.tell     # => 12
f.lineno   # => 1
f.rewind   # => 0
f.tell     # => 0
f.lineno   # => 0

Note that this method cannot be used with streams such as pipes, ttys, and sockets.

No documentation available
No documentation available

Seeks to the position given by integer offset (see Position) and constant whence, which is one of:

  • :CUR or IO::SEEK_CUR: Repositions the stream to its current position plus the given offset:

    f = File.open('t.txt')
    f.tell            # => 0
    f.seek(20, :CUR)  # => 0
    f.tell            # => 20
    f.seek(-10, :CUR) # => 0
    f.tell            # => 10
    
  • :END or IO::SEEK_END: Repositions the stream to its end plus the given offset:

    f = File.open('t.txt')
    f.tell            # => 0
    f.seek(0, :END)   # => 0  # Repositions to stream end.
    f.tell            # => 52
    f.seek(-20, :END) # => 0
    f.tell            # => 32
    f.seek(-40, :END) # => 0
    f.tell            # => 12
    
  • :SET or IO:SEEK_SET: Repositions the stream to the given offset:

    f = File.open('t.txt')
    f.tell            # => 0
    f.seek(20, :SET) # => 0
    f.tell           # => 20
    f.seek(40, :SET) # => 0
    f.tell           # => 40
    

Related: IO#pos=, IO#tell.

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.

Checks if ios starts with a BOM, and then consumes it and sets the external encoding. Returns the result encoding if found, or nil. If ios is not binmode or its encoding has been set already, an exception will be raised.

File.write("bom.txt", "\u{FEFF}abc")
ios = File.open("bom.txt", "rb")
ios.set_encoding_by_bom    #=>  #<Encoding:UTF-8>

File.write("nobom.txt", "abc")
ios = File.open("nobom.txt", "rb")
ios.set_encoding_by_bom    #=>  nil

Returns status information for ios as an object of type File::Stat.

f = File.new("testfile")
s = f.stat
"%o" % s.mode   #=> "100644"
s.blksize       #=> 4096
s.atime         #=> Wed Apr 09 08:53:54 CDT 2003

Returns the current sync mode of the stream. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered by Ruby internally. See also fsync.

f = File.open('t.tmp', 'w')
f.sync # => false
f.sync = true
f.sync # => true

Sets the sync mode for the stream to the given value; returns the given value.

Values for the sync mode:

  • true: All output is immediately flushed to the underlying operating system and is not buffered internally.

  • false: Output may be buffered internally.

Example;

f = File.open('t.tmp', 'w')
f.sync # => false
f.sync = true
f.sync # => true

Related: IO#fsync.

Behaves like IO#readpartial, except that it uses low-level system functions.

This method should not be used with other stream-reader methods.

Behaves like IO#seek, except that it:

  • Uses low-level system functions.

  • Returns the new position.

Writes the given object to self, which must be opened for writing (see Modes); returns the number bytes written. If object is not a string is converted via method to_s:

f = File.new('t.tmp', 'w')
f.syswrite('foo') # => 3
f.syswrite(30)    # => 2
f.syswrite(:foo)  # => 3

This methods should not be used with other stream-writer methods.

Returns the current position (in bytes) in self (see Position):

f = File.open('t.txt')
f.tell # => 0
f.gets # => "First line\n"
f.tell # => 12

Related: IO#pos=, IO#seek.

IO#pos is an alias for IO#tell.

An alias for fileno

Returns self.

An alias for isatty

Pushes back (“unshifts”) the given data onto the stream's buffer, placing the data so that it is next to be read; returns nil.

Note that:

  • Calling the method hs no effect with unbuffered reads (such as IO#sysread).

  • Calling rewind on the stream discards the pushed-back data.

When argument integer is given, uses only its low-order byte:

File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetbyte(0x41)   # => nil
f.read              # => "A012"
f.rewind
f.ungetbyte(0x4243) # => nil
f.read              # => "C012"

When argument string is given, uses all bytes:

File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetbyte('A')    # => nil
f.read              # => "A012"
f.rewind
f.ungetbyte('BCDE') # => nil
f.read              # => "BCDE012"

Pushes back (“unshifts”) the given data onto the stream's buffer, placing the data so that it is next to be read; returns nil.

Note that:

  • Calling the method hs no effect with unbuffered reads (such as IO#sysread).

  • Calling rewind on the stream discards the pushed-back data.

When argument integer is given, interprets the integer as a character:

File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetc(0x41)     # => nil
f.read             # => "A012"
f.rewind
f.ungetc(0x0442)   # => nil
f.getc.ord         # => 1090

When argument string is given, uses all characters:

File.write('t.tmp', '012')
f = File.open('t.tmp')
f.ungetc('A')      # => nil
f.read      # => "A012"
f.rewind
f.ungetc("\u0442\u0435\u0441\u0442") # => nil
f.getc.ord      # => 1090
f.getc.ord      # => 1077
f.getc.ord      # => 1089
f.getc.ord      # => 1090

Waits until the IO becomes ready for the specified events and returns the subset of events that become ready, or false when times out.

The events can be a bit mask of IO::READABLE, IO::WRITABLE or IO::PRIORITY.

Returns true immediately when buffered data is available.

Optional parameter mode is one of :read, :write, or :read_write.

Waits until IO is priority and returns true or false when times out.

Waits until IO is readable and returns true, or false when times out. Returns true immediately when buffered data is available.

Waits until IO is writable and returns true or false when times out.

Returns console size.

You must require 'io/console' to use this method.

Tries to set console size. The effect depends on the platform and the running environment.

You must require 'io/console' to use this method.

Writes each of the given objects to self, which must be opened for writing (see Modes); returns the total number bytes written; each of objects that is not a string is converted via method to_s:

$stdout.write('Hello', ', ', 'World!', "\n") # => 14
$stdout.write('foo', :bar, 2, "\n")          # => 8

Output:

Hello, World!
foobar2

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.

# Creates a pipe.
r, w = IO.pipe

# write_nonblock writes only 65536 bytes and return 65536.
# (The pipe size is 65536 bytes on this environment.)
s = "a" * 100000
p w.write_nonblock(s)     #=> 65536

# write_nonblock cannot write a byte and raise EWOULDBLOCK (EAGAIN).
p w.write_nonblock("b")   # Resource temporarily unavailable (Errno::EAGAIN)

If the write buffer is not empty, it is flushed at first.

When write_nonblock raises an exception kind of IO::WaitWritable, write_nonblock should not be called until io is writable for avoiding busy loop. This can be done as follows.

begin
  result = io.write_nonblock(string)
rescue IO::WaitWritable, Errno::EINTR
  IO.select(nil, [io])
  retry
end

Note that this doesn't guarantee to write all data in string. The length written is reported as result and it should be checked later.

On some platforms such as Windows, write_nonblock is not supported according to the kind of the IO object. In such cases, write_nonblock raises Errno::EBADF.

By specifying a keyword argument exception to false, you can indicate that write_nonblock should not raise an IO::WaitWritable exception, but return the symbol :wait_writable instead.