1

我有这个:

require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close

这打印:

contents are [] (14 bytes)

为什么没有实际显示内容?我在 Ruby 1.9.2 上。

4

2 回答 2

6

问题是您正在read文件中的当前 IO 指针处执行操作,该指针在您写入后已经位于末尾。你需要rewindread. 在您的示例中:

require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
t.rewind
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
于 2010-05-27T21:34:56.137 回答
2

您可能处于流的末尾,没有更多字节了。在写入之后和阅读之前,您应该倒回文件(重新打开或寻找位置 0)。

require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
t.seek 0
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
于 2010-05-27T21:31:13.557 回答