写入文件后无法打印文件

Can't print file after writing to it

出于某种原因,我无法在最后一行打印任何内容。

prev_std = STDOUT

$stdout = File.open(reportname, 'w')

# Several things happen to print to STDOUT here

$stdout = STDOUT

# Tell them that the report was written
puts "Report written to #{ reportname }"

# Slurp in the report ( FIXME )
reporttext = File.open(reportname, 'r') { |f| f.read }

# Print out the report after ( FIXME )
puts reporttext

我刚刚将报告写入文件,但不知何故无法将其读回屏幕。在这两种情况下,我在代码中使用完全相同的字符串来引用文件。检查 shell 提示符证明文件写入正确,但我仍然无法将其打印到屏幕上。

我做错了什么?

问题似乎出在文件未关闭上。更改 $stdout 不会关闭它曾经引用的文件对象。在将它重新分配给旧标准输出之前,将 $stdout.close 添加到该行。