In a Ruby script, I want to work on the first few lines of a source file (reading them with .readline
) and simply copy the rest of the source file to a target file (with IO.copy_stream
on the open files). However, IO.copy_stream
seems not to "see" the rest of the source file.
Here's how to reproduce the problem:
require 'rspec'
require 'tempfile'
def file_create(content)
Tempfile.open('foo') do |src|
src.print content
src.close
yield src.path
end
end
describe :copy_stream do
it 'copies the content of an open file' do
file_create("a\nb\n") do |path|
open(path) do |from|
Tempfile.open('bar') do |to|
IO.copy_stream(from, to)
to.close
expect(IO.read(to.path)).to eq "a\nb\n"
end
end
end
end
it 'copies the rest of an open file' do
file_create("a\nb\n") do |path|
open(path) do |from|
Tempfile.open('bar') do |to|
to.print from.readline
IO.copy_stream(from, to)
to.close
expect(IO.read(to.path)).to eq "a\nb\n"
end
end
end
end
end
That's the output:
Failures:
1) copy_stream copies the rest of an open file
Failure/Error: expect(IO.read(to.path)).to eq "a\nb\n"
expected: "a\nb\n"
got: "a\n"
(compared using ==)
Diff:
@@ -1,3 +1,2 @@
a
-b
[...]
2 examples, 1 failure
Failed examples:
rspec /workspaces/socbm378/johanabt/incstrip/spec/copy_stream_spec.rb:27 #
copy_stream copies the rest of an open file
Why does copy_stream
fail to copy the rest of the file?
I've found a simple work-around, but I'd like to understand the underlying problem. Here is my work-around:
def copy_stream2(from, to)
while (buf = from.read(16 * 1024))
to.print buf
end
end