End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
IO.copy_stream
static VALUE
rb_io_s_copy_stream(int argc, VALUE *argv, VALUE io)
{
VALUE src, dst, length, src_offset;
struct copy_stream_struct st;
MEMZERO(&st, struct copy_stream_struct, 1);
rb_scan_args(argc, argv, "22", &src, &dst, &length, &src_offset);
st.src = src;
st.dst = dst;
st.src_fptr = NULL;
st.dst_fptr = NULL;
if (NIL_P(length))
st.copy_length = (rb_off_t)-1;
else
st.copy_length = NUM2OFFT(length);
if (NIL_P(src_offset))
st.src_offset = (rb_off_t)-1;
else
st.src_offset = NUM2OFFT(src_offset);
rb_ensure(copy_stream_body, (VALUE)&st, copy_stream_finalize, (VALUE)&st);
return OFFT2NUM(st.total);
}
Copies from the given src to the given dst, returning the number of bytes copied.
-
The given
srcmust 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
:readpartialor method:read.
-
-
The given
dstmust 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:
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:
# 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:
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:
IO.copy_stream('t.txt', 't.tmp', 11, 11) # => 11 IO.read('t.tmp') # => "Second line"