Class: IO
Relationships & Source Files | |
Namespace Children | |
Modules:
| |
Classes:
| |
Extension / Inclusion / Inheritance Descendants | |
Subclasses:
|
|
Super Chains via Extension / Inclusion / Inheritance | |
Instance Chain:
self,
::Enumerable,
::File::Constants
|
|
Inherits: | Object |
Defined in: | io.c, file.c, prelude.rb |
Overview
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.
io/console
The io/console extension provides methods for interacting with the console. The console can be accessed from IO.console
or the standard input/output/error IO
objects.
Requiring io/console adds the following methods:
-
IO.console
-
IO#raw
-
IO#raw!
-
IO#cooked
-
IO#cooked!
-
IO#getch
-
IO#echo=
-
IO#echo?
-
IO#noecho
-
IO#winsize
-
IO#winsize=
-
IO#iflush
-
IO#ioflush
-
IO#oflush
Example:
require 'io/console'
rows, columns = $stdout.winsize
puts "Your screen is #{columns} wide and #{rows} tall"
Constant Summary
-
SEEK_CUR =
Set I/O position from the current position
INT2FIX(SEEK_CUR)
-
SEEK_DATA =
Set I/O position to the next location containing data
INT2FIX(SEEK_DATA)
-
SEEK_END =
Set I/O position from the end
INT2FIX(SEEK_END)
-
SEEK_HOLE =
Set I/O position to the next hole
INT2FIX(SEEK_HOLE)
-
SEEK_SET =
Set I/O position from the beginning
INT2FIX(SEEK_SET)
::File::Constants - Included
APPEND, BINARY, CREAT, DIRECT, DSYNC, EXCL, LOCK_EX, LOCK_NB, LOCK_SH, LOCK_UN, NOATIME, NOCTTY, NOFOLLOW, NONBLOCK, NULL, RDONLY, RDWR, RSYNC, SHARE_DELETE, SYNC, TMPFILE, TRUNC, WRONLY
Class Method Summary
-
.binread(name, [length [, offset]] ) ⇒ String
Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file).
-
.binwrite(name, string, [offset]) ⇒ Integer
Same as .write except opening the file in binary mode and ASCII-8BIT encoding (“wb:ASCII-8BIT”).
-
.copy_stream(src, dst)
copy_stream
copies src to dst. -
.for_fd(fd, mode [, opt]) ⇒ IO
Synonym for .new.
-
.foreach(name, sep=$/ [, open_args]) {|line| ... } ⇒ nil
Executes the block for every line in the named I/O port, where lines are separated by sep.
-
.open(filename, mode="r" [, opt]) ⇒ File
Alias for File.open.
-
.pipe ⇒ IO
IO
.pipe(…) {|read_io, write_io| … } -
.popen([env,] cmd, mode="r" [, opt]) ⇒ IO
Runs the specified command as a subprocess; the subprocess's standard input and output will be connected to the returned
IO
object. -
.read(name, [length [, offset]] [, opt] ) ⇒ String
Opens the file, optionally seeks to the given
offset
, then returnslength
bytes (defaulting to the rest of the file). -
.readlines(name, sep=$/ [, open_args]) ⇒ Array
Reads the entire file specified by name as individual lines, and returns those lines in an array.
-
.select(read_array [, write_array [, error_array [, timeout]]]) ⇒ Array?
Alias for Kernel.select.
-
.sysopen(path, [mode, [perm]]) ⇒ Integer
Opens the given path, returning the underlying file descriptor as a ::Integer.
-
.try_convert(obj) ⇒ IO?
Try to convert obj into an
IO
, using to_io method. -
.write(name, string [, offset]) ⇒ Integer
Opens the file, optionally seeks to the given offset, writes string, then returns the length written.
Instance Attribute Summary
-
#autoclose=(bool) ⇒ Boolean
rw
Sets auto-close flag.
-
#autoclose? ⇒ Boolean
rw
Returns
true
if the underlying file descriptor of ios will be closed automatically at its finalization, otherwisefalse
. -
#close_on_exec=(bool) ⇒ Boolean
rw
Sets a close-on-exec flag.
-
#close_on_exec? ⇒ Boolean
rw
Returns
true
if ios will be closed on exec. -
#lineno ⇒ Integer
rw
Returns the current line number in ios.
-
#lineno=(integer) ⇒ Integer
rw
Manually sets the current line number to the given value.
-
#pos ⇒ Integer
(also: #tell)
rw
Returns the current offset (in bytes) of ios.
-
#pos=(integer) ⇒ Integer
rw
Seeks to the given position (in bytes) in ios.
-
#sync ⇒ Boolean
rw
Returns the current “sync mode'' of ios.
-
#sync=(boolean) ⇒ Boolean
rw
Sets the “sync mode'' to
true
orfalse
. -
#binmode ⇒ IO
readonly
Puts ios into binary mode.
-
#binmode? ⇒ Boolean
readonly
Returns
true
if ios is binmode. -
#closed? ⇒ Boolean
readonly
Returns
true
if ios is completely closed (for duplex streams, both reader and writer),false
otherwise. -
#eof ⇒ Boolean
(also: #eof?)
readonly
Returns true if ios is at end of file that means there are no more data to read.
-
#eof? ⇒ Boolean
readonly
Alias for #eof.
-
#isatty ⇒ Boolean
readonly
Alias for #tty?.
-
#tell ⇒ Integer
readonly
Alias for #pos.
-
#tty? ⇒ Boolean
(also: #isatty)
readonly
Returns
true
if ios is associated with a terminal device (tty),false
otherwise.
::Enumerable - Included
Instance Method Summary
-
#<<(obj) ⇒ IO
::String Output—Writes obj to ios.
-
#advise(advice, offset = 0, len = 0) ⇒ nil
Announce an intention to access data from the current file in a specific pattern.
-
#bytes
This is a deprecated alias for #each_byte.
-
#chars
This is a deprecated alias for #each_char.
-
#close ⇒ nil
Closes ios and flushes any pending writes to the operating system.
-
#close_read ⇒ nil
Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe).
-
#close_write ⇒ nil
Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe).
-
#codepoints
This is a deprecated alias for #each_codepoint.
-
#each(sep = $/) {|line| ... } ⇒ IO
(also: #each_line)
ios.each_line(sep=$/) {|line| block } -> ios.
-
#each_byte {|byte| ... } ⇒ IO
Calls the given block once for each byte (0..255) in ios, passing the byte as an argument.
-
#each_char {|c| ... } ⇒ IO
Calls the given block once for each character in ios, passing the character as an argument.
-
#each_codepoint {|c| ... } ⇒ IO
Passes the ::Integer ordinal of each character in ios, passing the codepoint as an argument.
-
#each(sep = $/) {|line| ... } ⇒ IO
Alias for #each.
-
#external_encoding ⇒ Encoding
Returns the ::Encoding object that represents the encoding of the file.
-
#fcntl(integer_cmd, arg) ⇒ Integer
Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams.
-
#fdatasync ⇒ 0?
Immediately writes all buffered data in ios to disk.
-
#fileno ⇒ Integer
Alias for #to_i.
-
#flush ⇒ IO
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).
-
#fsync ⇒ 0?
Immediately writes all buffered data in ios to disk.
-
#getbyte ⇒ Integer?
Gets the next 8-bit byte (0..255) from ios.
-
#getc ⇒ String?
Reads a one-character string from ios.
-
#gets(sep = $/) ⇒ String?
Reads the next “line'' from the I/O stream; lines are separated by sep.
-
#new(fd [, mode] [, opt]) ⇒ IO
constructor
Returns a new
IO
object (a stream) for the given integer file descriptorfd
andmode
string. -
#inspect ⇒ String
Return a string describing this
IO
object. -
#internal_encoding ⇒ Encoding
Returns the ::Encoding of the internal string if conversion is specified.
-
#ioctl(integer_cmd, arg) ⇒ Integer
Provides a mechanism for issuing low-level commands to control or query I/O devices.
-
#lines(*args)
This is a deprecated alias for #each_line.
-
#pid ⇒ Integer
Returns the process ID of a child process associated with ios.
-
#print ⇒ nil
Writes the given object(s) to ios.
-
#printf(format_string [, obj, ...]) ⇒ nil
Formats and writes to ios, converting parameters under control of the format string.
-
#putc(obj) ⇒ Object
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.
-
#puts(obj, ...) ⇒ nil
Writes the given object(s) to ios.
-
#read([length [, outbuf]]) ⇒ String, ...
Reads length bytes from the I/O stream.
-
#read_nonblock(maxlen [, options]) ⇒ String
Reads at most maxlen bytes from ios using the read(2) system call after O_NONBLOCK is set for the underlying file descriptor.
-
#readbyte ⇒ Integer
Reads a byte as with #getbyte, but raises an ::EOFError on end of file.
-
#readchar ⇒ String
Reads a one-character string from ios.
-
#readline(sep = $/) ⇒ String
Reads a line as with #gets, but raises an ::EOFError on end of file.
-
#readlines(sep = $/) ⇒ Array
Reads all of the lines in ios, and returns them in anArray.
-
#readpartial(maxlen) ⇒ String
Reads at most maxlen bytes from the I/O stream.
-
#reopen(other_IO) ⇒ IO
Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path.
-
#rewind ⇒ 0
Positions ios to the beginning of input, resetting #lineno to zero.
-
#seek(amount, whence = IO::SEEK_SET) ⇒ 0
Seeks to a given offset anInteger in the stream according to the value of whence:
-
#set_encoding(ext_enc) ⇒ IO
If single argument is specified, read string from io is tagged with the encoding specified.
-
#stat ⇒ stat
Returns status information for ios as an object of type ::File::Stat.
-
#sysread(maxlen[, outbuf]) ⇒ String
Reads maxlen bytes from ios using a low-level read and returns them as a string.
-
#sysseek(offset, whence = IO::SEEK_SET) ⇒ Integer
Seeks to a given offset in the stream according to the value of whence (see #seek for values of whence).
-
#syswrite(string) ⇒ Integer
Writes the given string to ios using a low-level write.
-
#to_i ⇒ Integer
(also: #fileno)
Returns an integer representing the numeric file descriptor for ios.
-
#to_io ⇒ IO
Returns ios.
-
#ungetbyte(string) ⇒ nil
Pushes back bytes (passed as a parameter) onto ios, such that a subsequent buffered read will return it.
-
#ungetc(string) ⇒ nil
Pushes back one character (passed as a parameter) onto ios, such that a subsequent buffered character read will return it.
-
#write(string) ⇒ Integer
Writes the given string to ios.
-
#write_nonblock(string) ⇒ Integer
Writes the given string to ios using the write(2) system call after O_NONBLOCK is set for the underlying file descriptor.
::Enumerable - Included
#chunk | Enumerates over the items, chunking them together based on the return value of the block. |
#chunk_while | Creates an enumerator for each chunked elements. |
#collect | Alias for Enumerable#map. |
#collect_concat | Alias for Enumerable#flat_map. |
#count | Returns the number of items in |
#cycle | Calls block for each element of enum repeatedly n times or forever if none or |
#detect | Alias for Enumerable#find. |
#drop | Drops first n elements from enum, and returns rest elements in an array. |
#drop_while | Drops elements up to, but not including, the first element for which the block returns |
#each_cons | Iterates the given block for each array of consecutive <n> elements. |
#each_entry | Calls block once for each element in |
#each_slice | Iterates the given block for each slice of <n> elements. |
#each_with_index | Calls block with two arguments, the item and its index, for each item in enum. |
#each_with_object | Iterates the given block for each element with an arbitrary object given, and returns the initially given object. |
#entries | Alias for Enumerable#to_a. |
#find | Passes each entry in enum to block. |
#find_all | Alias for Enumerable#select. |
#find_index | Compares each entry in enum with value or passes to block. |
#first | Returns the first element, or the first |
#flat_map | Returns a new array with the concatenated results of running block once for every element in enum. |
#grep | Returns an array of every element in enum for which |
#grep_v | Inverted version of Enumerable#grep. |
#group_by | Groups the collection by result of the block. |
#include? | Alias for Enumerable#member?. |
#inject | Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. |
#lazy | Returns a lazy enumerator, whose methods map/collect, flat_map/collect_concat, select/find_all, reject, grep, grep_v, zip, take, take_while, drop, and drop_while enumerate values only on an as-needed basis. |
#map | Returns a new array with the results of running block once for every element in enum. |
#max | Returns the object in enum with the maximum value. |
#max_by | Returns the object in enum that gives the maximum value from the given block. |
#member? | Returns |
#min | Returns the object in enum with the minimum value. |
#min_by | Returns the object in enum that gives the minimum value from the given block. |
#minmax | Returns a two element array which contains the minimum and the maximum value in the enumerable. |
#minmax_by | Returns a two element array containing the objects in enum that correspond to the minimum and maximum values respectively from the given block. |
#partition | Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest. |
#reduce | Alias for Enumerable#inject. |
#reject | Returns an array for all elements of |
#reverse_each | Builds a temporary array and traverses that array in reverse order. |
#select | Returns an array containing all elements of |
#slice_after | Creates an enumerator for each chunked elements. |
#slice_before | Creates an enumerator for each chunked elements. |
#slice_when | Creates an enumerator for each chunked elements. |
#sort | Returns an array containing the items in enum sorted. |
#sort_by | Sorts enum using a set of keys generated by mapping the values in enum through the given block. |
#sum | Returns the sum of elements in an ::Enumerable. |
#take | Returns first n elements from enum. |
#take_while | Passes elements to the block until the block returns |
#to_a | Returns an array containing the items in enum. |
#to_h | Returns the result of interpreting enum as a list of |
#uniq | Returns a new array by removing duplicate values in |
#zip | Takes one element from enum and merges corresponding elements from each args. |
Constructor Details
#new(fd [, mode] [, opt]) ⇒ IO
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 .sysopen and .for_fd.
.new is called by various ::File and IO
opening methods such as .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
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
, thefd
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.
Class Method Details
.binread(name, [length [, offset]] ) ⇒ String
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 "
Same as .write except opening the file in binary mode and ASCII-8BIT encoding (“wb:ASCII-8BIT”).
.copy_stream(src, dst)
.copy_stream(src, dst, copy_length)
.copy_stream(src, dst, copy_length, src_offset)
copy_stream
copies src to dst. src and dst is either a filename or an IO
.
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
, copy_stream
doesn't move the current file offset.
.for_fd(fd, mode [, opt]) ⇒ IO
Synonym for .new.
.foreach(name, sep=$/ [, open_args]) {|line| ... } ⇒ nil
.foreach(name, limit [, open_args]) {|line| ... } ⇒ nil
.foreach(name, sep, limit [, open_args]) {|line| ... } ⇒ nil
.foreach(...) ⇒ Enumerator
nil
.foreach(name, limit [, open_args]) {|line| ... } ⇒ nil
.foreach(name, sep, limit [, open_args]) {|line| ... } ⇒ nil
.foreach(...) ⇒ Enumerator
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.
IO.foreach("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 .read for detail.
Alias for File.open. With no associated block, 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.
See .new for a description of the fd
, mode
and opt
parameters.
.pipe ⇒ IO
.pipe(ext_enc) ⇒ IO
.pipe("ext_enc:int_enc" [, opt]) ⇒ IO
.pipe(ext_enc, int_enc [, opt]) ⇒ IO
IO
.pipe(ext_enc) ⇒ IO
.pipe("ext_enc:int_enc" [, opt]) ⇒ IO
.pipe(ext_enc, int_enc [, opt]) ⇒ IO
IO
.pipe(…) {|read_io, write_io| … }
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>
.popen([env,] cmd, mode="r" [, opt]) ⇒ IO
.popen([env,] cmd, mode="r" [, opt]) {|io| ... } ⇒ Object
IO
.popen([env,] cmd, mode="r" [, opt]) {|io| ... } ⇒ Object
Runs the specified command as a subprocess; the subprocess's standard input and output will be connected to the returned IO
object.
The PID of the started process can be obtained by #pid method.
cmd is a string or an array as follows.
cmd:
"-" : fork
commandline : command line string which is passed to a shell
[env, cmdname, arg1, ..., opts] : command name and zero or more arguments (no shell)
[env, [cmdname, argv0], arg1, ..., opts] : command name, argv[0] and zero or more arguments (no shell)
(env and opts are optional.)
If cmd is a ::String “-
'', then a new instance of Ruby is started as the subprocess.
If cmd is an ::Array of ::String, then it will be used as the subprocess's argv
bypassing a shell. The array can contains a hash at first for environments and a hash at last for options similar to spawn
.
The default mode for the new file object is “r'', but mode may be set to any of the modes listed in the description for class IO
. The last argument opt qualifies mode.
# 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
# spawn option. See the document of Kernel.spawn.
IO.popen(["ls", "/", :err=>[:child, :out]]) {|ls_io|
ls_result_with_error = ls_io.read
}
# spawn options can be mixed with IO options
IO.popen(["ls", "/"], :err=>[:child, :out]) {|ls_io|
ls_result_with_error = ls_io.read
}
Raises exceptions which .pipe and Kernel.spawn raise.
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 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.
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
}
produces:
["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;
.read(name, [length [, offset]] [, opt] ) ⇒ String
Opens the file, optionally seeks to the given offset
, then returns length
bytes (defaulting to the rest of the file). read
ensures the file is closed before returning.
If name
starts with a pipe character ("|"
), a subprocess is created in the same way as Kernel.open, and its output is returned.
Options
The options hash accepts the following keys:
- :encoding
-
string or encoding
Specifies the encoding of the read string.
:encoding
will be ignored iflength
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 IO.new for the list of possible modes.
- :open_args
-
array
Specifies arguments for open() as an array. This key can not be used in combination with either
:encoding
or:mode
.
Examples:
IO.read("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
IO.read("testfile", 20) #=> "This is line one\nThi"
IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
IO.read("binfile", mode: "rb") #=> "\xF7\x00\x00\x0E\x12"
Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep.
a = IO.readlines("testfile")
a[0] #=> "This is line one\n"
If the last argument is a hash, it's the keyword argument to open. See .read for detail.
.select(read_array [, write_array [, error_array [, timeout]]]) ⇒ Array?
Alias for Kernel.select. 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.
select
peeks the buffer of IO
objects for testing readability. If the IO
buffer is not empty, 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 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 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 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 select
is preferred for IO
like objects such as OpenSSL::SSL::SSLSocket
. It has #to_io method to return underlying IO
object. select
calls #to_io to obtain the file descriptor to wait.
This means that readability notified by select
doesn't mean readability from OpenSSL::SSL::SSLSocket
object.
The most likely situation is that OpenSSL::SSL::SSLSocket
buffers some data. select
doesn't see the buffer. So 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, 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 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 select
before #readpartial works well as usual. However it is not the best way to use select
.
The writability notified by select(2) doesn't show how many bytes writable. #write method blocks until given whole string is written. So, IO#write(two or more bytes)
can block after writability is notified by select
. #write_nonblock is required to avoid the blocking.
Blocking write (.write) can be emulated using #write_nonblock and 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
.sysopen(path, [mode, [perm]]) ⇒ Integer
Opens the given path, returning the underlying file descriptor as a ::Integer.
IO.sysopen("testfile") #=> 3
.try_convert(obj) ⇒ IO
?
Try to convert obj into an IO
, using to_io method. Returns converted IO
or nil
if obj cannot be converted for any reason.
IO.try_convert(STDOUT) #=> STDOUT
IO.try_convert("STDOUT") #=> nil
require 'zlib'
f = open("/tmp/zz.gz") #=> #<File:/tmp/zz.gz>
z = Zlib::GzipReader.open(f) #=> #<Zlib::GzipReader:0x81d8744>
IO.try_convert(z) #=> #<File:/tmp/zz.gz>
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.
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"
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
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.
Instance Attribute Details
#autoclose=(bool) ⇒ Boolean
(rw)
#autoclose? ⇒ Boolean
(rw)
Returns true
if the underlying file descriptor of ios will be closed automatically at its finalization, otherwise false
.
#binmode ⇒ IO
(readonly)
Puts ios into binary mode. Once a stream is in binary mode, it cannot be reset to nonbinary mode.
-
newline conversion disabled
-
encoding conversion disabled
-
content is treated as ASCII-8BIT
#binmode? ⇒ Boolean
(readonly)
Returns true
if ios is binmode.
#close_on_exec=(bool) ⇒ Boolean
(rw)
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.
#close_on_exec? ⇒ Boolean
(rw)
Returns true
if ios will be closed on exec.
f = open("/dev/null")
f.close_on_exec? #=> false
f.close_on_exec = true
f.close_on_exec? #=> true
f.close_on_exec = false
f.close_on_exec? #=> false
#closed? ⇒ Boolean
(readonly)
Returns true
if ios is completely closed (for duplex streams, both reader and writer), false
otherwise.
f = File.new("testfile")
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
#eof ⇒ Boolean
(readonly)
#eof? ⇒ Boolean
Also known as: #eof?
Boolean
(readonly)
#eof? ⇒ Boolean
Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an ::IOError will be raised.
f = File.new("testfile")
dummy = f.readlines
f.eof #=> true
If ios is a stream such as pipe or socket, #eof? 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 blocking
r, w = IO.pipe
Thread.new { sleep 1; w.puts "a" }
r.eof? #=> false after 1 second blocking
r, w = IO.pipe
r.eof? # blocks forever
Note that #eof? reads data to the input byte buffer. So #sysread may not behave as you intend with #eof?, unless you call #rewind first (which is not available for some streams).
#eof ⇒ Boolean
(readonly)
#eof? ⇒ Boolean
Boolean
(readonly)
#eof? ⇒ Boolean
Alias for #eof.
#isatty ⇒ Boolean
(readonly)
#tty? ⇒ Boolean
Boolean
(readonly)
#tty? ⇒ Boolean
Alias for #tty?.
#lineno ⇒ Integer (rw)
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.
Methods that use $/
like #each, #lines and #readline will also increment lineno
.
See also the $.
variable.
f = File.new("testfile")
f.lineno #=> 0
f.gets #=> "This is line one\n"
f.lineno #=> 1
f.gets #=> "This is line two\n"
f.lineno #=> 2
#lineno=(integer) ⇒ Integer (rw)
Also known as: #tell
#pos=(integer) ⇒ Integer (rw)
#sync ⇒ Boolean
(rw)
#sync=(boolean) ⇒ Boolean
(rw)
Alias for #pos.
#isatty ⇒ Boolean
(readonly)
#tty? ⇒ Boolean
Also known as: #isatty
Boolean
(readonly)
#tty? ⇒ Boolean
Instance Method Details
#<<(obj) ⇒ IO
::String Output—Writes obj to ios. obj will be converted to a string using to_s
.
$stdout << "Hello " << "world!\n"
produces:
Hello world!
#advise(advice, offset = 0, len = 0) ⇒ nil
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.
#bytes
This is a deprecated alias for #each_byte.
#chars
This is a deprecated alias for #each_char.
#close ⇒ nil
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 .popen, close
sets $?
.
Calling this method on closed IO
object is just ignored since Ruby 2.3.
#close_read ⇒ nil
Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an ::IOError if the stream is not duplexed.
f = IO.popen("/bin/sh","r+")
f.close_read
f.readlines
produces:
prog.rb:3:in `readlines': not opened for reading (IOError)
from prog.rb:3
#close_write ⇒ nil
Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an ::IOError if the stream is not duplexed.
f = IO.popen("/bin/sh","r+")
f.close_write
f.print "nowhere"
produces:
prog.rb:3:in `write': not opened for writing (IOError)
from prog.rb:3:in `print'
from prog.rb:3
#codepoints
This is a deprecated alias for #each_codepoint.
#each(sep = $/) {|line| ... } ⇒ IO
#each(limit) {|line| ... } ⇒ IO
#each(sep, limit) {|line| ... } ⇒ IO
#each(...) ⇒ Enumerator
Also known as: #each_line
IO
#each(limit) {|line| ... } ⇒ IO
#each(sep, limit) {|line| ... } ⇒ IO
#each(...) ⇒ Enumerator
ios.each_line(sep=$/) {|line| block } -> ios
ios.each_line(limit) {|line| block } -> ios
ios.each_line(sep, limit) {|line| block } -> ios
ios.each_line(...) -> an_enumerator
Executes the block for every line in ios, where lines are separated by sep. ios must be opened for reading or an ::IOError will be raised.
If no block is given, an enumerator is returned instead.
f = File.new("testfile")
f.each {|line| puts "#{f.lineno}: #{line}" }
produces:
1: This is line one
2: This is line two
3: This is line three
4: And so on...
#each_byte {|byte| ... } ⇒ IO
#each_byte ⇒ Enumerator
IO
#each_byte ⇒ Enumerator
Calls the given block once for each byte (0..255) in ios, passing the byte as an argument. The stream must be opened for reading or an ::IOError will be raised.
If no block is given, an enumerator is returned instead.
f = File.new("testfile")
checksum = 0
f.each_byte {|x| checksum ^= x } #=> #<File:testfile>
checksum #=> 12
#each_char {|c| ... } ⇒ IO
#each_char ⇒ Enumerator
IO
#each_char ⇒ Enumerator
#each_codepoint {|c| ... } ⇒ IO
#codepoints {|c| ... } ⇒ IO
#each_codepoint ⇒ Enumerator
#codepoints ⇒ Enumerator
IO
#codepoints {|c| ... } ⇒ IO
#each_codepoint ⇒ Enumerator
#codepoints ⇒ Enumerator
#each(sep = $/) {|line| ... } ⇒ IO
#each(limit) {|line| ... } ⇒ IO
#each(sep, limit) {|line| ... } ⇒ IO
#each(...) ⇒ Enumerator
IO
#each(limit) {|line| ... } ⇒ IO
#each(sep, limit) {|line| ... } ⇒ IO
#each(...) ⇒ Enumerator
Alias for #each.
#external_encoding ⇒ Encoding
Returns the ::Encoding object that represents the encoding of the file. If io is in write mode and no encoding is specified, returns nil
.
#fcntl(integer_cmd, arg) ⇒ Integer
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.
#fdatasync ⇒ 0
?
Immediately writes all buffered data in ios to disk.
If the underlying operating system does not support fdatasync(2), #fsync is called instead (which might raise a ::NotImplementedError).
Alias for #to_i.
#flush ⇒ IO
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:
no newline
#fsync ⇒ 0
?
Immediately writes all buffered data in ios to disk. Note that fsync
differs from using #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).
#getbyte ⇒ Integer?
#getc ⇒ String?
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"
If IO contains multibyte characters byte then gets(1)
returns character entirely:
# Russian characters take 2 bytes
File.write("testfile", "\u{442 435 441 442}")
File.open("testfile") {|f|f.gets(1)} #=> "\u0442"
File.open("testfile") {|f|f.gets(2)} #=> "\u0442"
File.open("testfile") {|f|f.gets(3)} #=> "\u0442\u0435"
File.open("testfile") {|f|f.gets(4)} #=> "\u0442\u0435"
#inspect ⇒ String
Return a string describing this IO
object.
#internal_encoding ⇒ Encoding
Returns the ::Encoding of the internal string if conversion is specified. Otherwise returns nil
.
#ioctl(integer_cmd, arg) ⇒ Integer
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.
#lines(*args)
This is a deprecated alias for #each_line.
#pid ⇒ Integer
#print ⇒ nil
#print(obj, ...) ⇒ nil
nil
#print(obj, ...) ⇒ nil
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.
#printf(format_string [, obj, ...]) ⇒ nil
Formats and writes to ios, converting parameters under control of the format string. See Kernel#sprintf
for details.
#putc(obj) ⇒ Object
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.
$stdout.putc "A"
$stdout.putc 65
produces:
AA
#puts(obj, ...) ⇒ nil
Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns nil
.
The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its to_s
method. If called without arguments, outputs a single newline.
$stdout.puts("this", "is", ["a", "test"])
produces:
this
is
a
test
Note that puts
always uses newlines and is not affected by the output record separator ($\
).
#read([length [, outbuf]]) ⇒ String, ...
Reads length bytes from the I/O stream.
length must be a non-negative integer or nil
.
If length is a positive integer, read
tries to read length bytes without any conversion (binary mode). It returns nil
if an EOF is encountered before anything can be read. Fewer than length bytes are returned if an EOF is encountered during the read. In the case of an integer length, the resulting string is always in ASCII-8BIT encoding.
If length is omitted or is nil
, it reads until EOF and the encoding conversion is applied, if applicable. A string is returned even if EOF is encountered before any data is read.
If length is zero, it returns an empty string (""
).
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.
When this method is called at end of file, it returns nil
or ""
, depending on length: read
, read(nil)
, and read(0)
return ""
, read(positive_integer)
returns nil
.
f = File.new("testfile")
f.read(16) #=> "This is line one"
# read whole file
open("file") do |f|
data = f.read # This returns a string even if the file is empty.
# ...
end
# iterate over fixed length records
open("fixed-record-file") do |f|
while record = f.read(256)
# ...
end
end
# iterate over variable length records,
# each record is prefixed by its 32-bit length
open("variable-record-file") do |f|
while len = f.read(4)
len = len.unpack("N")[0] # 32-bit length
record = f.read(len) # This returns a string even if len is 0.
end
end
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 length (or until EOF). This behavior is preserved even if ios 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.
#read_nonblock(maxlen [, options]) ⇒ String
#read_nonblock(maxlen, outbuf [, options]) ⇒ outbuf
outbuf
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.
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 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.
# File 'prelude.rb', line 75
def read_nonblock(len, buf = nil, exception: true) __read_nonblock(len, buf, exception) end
#readbyte ⇒ Integer
Reads a byte as with #getbyte, but raises an ::EOFError on end of file.
#readchar ⇒ String
Reads a one-character string from ios. Raises an ::EOFError on end of file.
f = File.new("testfile")
f.readchar #=> "h"
f.readchar #=> "e"
Reads a line as with #gets, but raises an ::EOFError on end of file.
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.
f = File.new("testfile")
f.readlines[0] #=> "This is line one\n"
#readpartial(maxlen) ⇒ String
#readpartial(maxlen, outbuf) ⇒ outbuf
outbuf
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.
-
the byte buffer in the
IO
object is empty. -
the content of the stream is empty.
-
the stream is not reached to EOF.
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.
r, w = IO.pipe # buffer pipe content
w << "abc" # "" "abc".
r.readpartial(4096) #=> "abc" "" ""
r.readpartial(4096) # blocks because buffer and pipe is empty.
r, w = IO.pipe # buffer pipe content
w << "abc" # "" "abc"
w.close # "" "abc" EOF
r.readpartial(4096) #=> "abc" "" EOF
r.readpartial(4096) # raises EOFError
r, w = IO.pipe # buffer pipe content
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" "" ""
Note that readpartial behaves 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
andErrno::EINTR
. When readpartial meets EWOULDBLOCK and EINTR by read system call, readpartial retry the system call.
The latter means that readpartial is nonblocking-flag insensitive. It blocks on the situation #sysread causes Errno::EWOULDBLOCK
as if the fd is blocking mode.
#reopen(other_IO) ⇒ IO
#reopen(path, mode_str) ⇒ IO
IO
#reopen(path, mode_str) ⇒ IO
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.
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"
#rewind ⇒ 0
#seek(amount, whence = IO::SEEK_SET) ⇒ 0
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_
Example:
f = File.new("testfile")
f.seek(-13, IO::SEEK_END) #=> 0
f.readline #=> "And so on...\n"
#set_encoding(ext_enc) ⇒ IO
#set_encoding("ext_enc:int_enc") ⇒ IO
#set_encoding(ext_enc, int_enc) ⇒ IO
#set_encoding("ext_enc:int_enc", opt) ⇒ IO
#set_encoding(ext_enc, int_enc, opt) ⇒ IO
IO
#set_encoding("ext_enc:int_enc") ⇒ IO
#set_encoding(ext_enc, int_enc) ⇒ IO
#set_encoding("ext_enc:int_enc", opt) ⇒ IO
#set_encoding(ext_enc, int_enc, opt) ⇒ IO
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.
#stat ⇒ stat
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
#sysread(maxlen[, outbuf]) ⇒ String
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.
f = File.new("testfile")
f.sysread(16) #=> "This is line one"
#sysseek(offset, whence = IO::SEEK_SET) ⇒ Integer
#syswrite(string) ⇒ Integer
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.
f = File.new("out", "w")
f.syswrite("ABCDEF") #=> 6
Also known as: #fileno
#to_io ⇒ IO
Returns ios.
#ungetbyte(string) ⇒ nil
#ungetbyte(integer) ⇒ nil
nil
#ungetbyte(integer) ⇒ nil
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 #sysread).
f = File.new("testfile") #=> #<File:testfile>
b = f.getbyte #=> 0x38
f.ungetbyte(b) #=> nil
f.getbyte #=> 0x38
#ungetc(string) ⇒ nil
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 #sysread).
f = File.new("testfile") #=> #<File:testfile>
c = f.getc #=> "8"
f.ungetc(c) #=> nil
f.getc #=> "8"
#write(string) ⇒ Integer
Writes the given string to ios. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s
. Returns the number of bytes written.
count = $stdout.write("This is a test\n")
puts "That was #{count} bytes of data"
produces:
This is a test
That was 15 bytes of data
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.
# File 'prelude.rb', line 133
def write_nonblock(buf, exception: true) __write_nonblock(buf, exception) end