新手问题 File.read 读不全文件

davidlichao · 2014年12月30日 · 最后由 jasl 回复于 2014年12月31日 · 2784 次阅读

代码和环境如下,File.read 只能输出到 1860 行。😰

RUBY VERSION: 2.2.0 (2014-12-25 patchlevel 0) [x86_64-linux]
class Debug
  def initialize
    file = File.new("debug.txt", "w+:UTF-8")
    3000.times { |row| file.puts row }
    puts File.read("debug.txt")
  end
end

Debug.new
1 楼 已删除

问题解决了,需要关闭文件。😓 修复后的代码如下:

class Debug
  def initialize
    file = File.new("debug.txt", "w+:UTF-8")
    3000.times { |row| file.puts row }

    # close the file
    file.close

    puts File.read("debug.txt")
  end
end

Debug.new

另外,如果使用FileUtils.mv(original_file, target_file)的话,需要关闭original_file

你也可以用 rw+ 方式打开文件

file = File.new("debug.txt", "rw+:UTF-8")
3000.times { |row| file.puts row }

file.rewind # 将文件指针指回文件开头

puts file.read

大概是这样子~

设置 async = false 呢,没测

#4 楼 @hooooopo 应该是他之前的 File.open 占用了文件指针,这是操作系统层面的事情了

不一定要关闭文件,只要 file.flush 应该就可以了,关闭会带上 flush 操作。

追加: file.sync = true 也可以,但是要放在写之前。

#5 楼 @jasl http://blog.rubybestpractices.com/posts/ewong/013-IO-dup-and-dup-system-call.html

文件只有一个,但文件描述符和 Ruby IO 对象有多个,他这个就是没写进去..

#3 楼 @jasl 多谢指教!另外有rw+这个模式吗?我在 irb 里执行了一下,返回了ArgumentError: invalid access mode rw+:UTF-8

#8 楼 @davidlichao 对。。是没有 - -

需要 登录 后方可回复, 如果你还没有账号请 注册新账号