Method: IO.copy_stream
- Defined in:
- io.c
.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
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"
13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 |
# File 'io.c', line 13405 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); } |