Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

IO.copy_stream

IO.copy_stream(src, dst, src_length = nil, src_offset = 0) → integer

Copies from the given src to the given dst, returning the number of bytes copied.

  • The given src must be one of the following:

    • The path to a readable file, from which source data is to be read.

    • An IO-like object, opened for reading and capable of responding to method :readpartial or method :read.

  • The given dst must be one of the following:

    • The path to a writable file, to which data is to be written.

    • An IO-like object, opened for writing and capable of responding to method :write.

The examples here use file t.txt as source:

Example
File.read('t.txt')
# => "First line\nSecond line\n\nThird line\nFourth line\n"
File.read('t.txt').size # => 47

If only arguments src and dst are given, the entire source stream is copied:

Example
# Paths.
IO.copy_stream('t.txt', 't.tmp')  # => 47

# IOs (recall that a File is also an IO).
src_io = File.open('t.txt', 'r') # => #<File:t.txt>
dst_io = File.open('t.tmp', 'w') # => #<File:t.tmp>
IO.copy_stream(src_io, dst_io)   # => 47
src_io.close
dst_io.close

With argument src_length a non-negative integer, no more than that many bytes are copied:

Example
IO.copy_stream('t.txt', 't.tmp', 10) # => 10
File.read('t.tmp')                   # => "First line"

With argument src_offset also given, the source stream is read beginning at that offset:

Example
IO.copy_stream('t.txt', 't.tmp', 11, 11) # => 11
IO.read('t.tmp')                         # => "Second line"