ruby - Ruby 的 IO.copy_stream 不能与 readline 正确交互?
问题描述
在 Ruby 脚本中,我想处理源文件的前几行(使用 读取它们.readline
),然后简单地将源文件的其余部分复制到目标文件(使用IO.copy_stream
打开的文件)。但是,IO.copy_stream
似乎没有“看到”源文件的其余部分。
以下是重现问题的方法:
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
这就是输出:
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
为什么copy_stream
无法复制文件的其余部分?
我找到了一个简单的解决方法,但我想了解潜在的问题。这是我的解决方法:
def copy_stream2(from, to)
while (buf = from.read(16 * 1024))
to.print buf
end
end