【问题标题】:Can't print file after writing to it写入文件后无法打印文件
【发布时间】:2015-04-08 20:32:53
【问题描述】:

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

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 提示符处检查证明文件已正确写入,但我仍然无法将其打印到屏幕上。

我在这里做错了什么?

【问题讨论】:

    标签: ruby io


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多