Ruby tempfile损坏了二进制文件

时间:2017-07-11 18:11:06

标签: ruby windows temporary-files

经过大量挖掘后,我发现RubyZip可以破坏二进制文件。仔细看后,似乎 variable = Left(Sheet1.[C2],InStr(Sheet1.[C2],".")-1) 类无法正确重新打开二进制文件。要演示效果,请使用以下脚本:

Tempfile

我使用的require 'tempfile' tmp = Tempfile.new('test.bin', Dir.getwd) File.open('test.bin', 'rb') { |h| IO.copy_stream(h, tmp) } # => 2 # 2 is the expected number of bytes tmp.close # temporary file (looking in OS) now really IS 2 bytes in size tmp.open # temporary file (looking in OS) now is 1 byte in size tmp.binmode # temporary file (looking in OS) still has the wrong number of bytes (1) tmp.read.length # => 1 # And here is the problem I keep bumping into 文件只包含两个字节:test.bin。在临时文件损坏后,它包含1个字节:00 1a。如果重要的话我正在运行Windows。

有什么东西我不见了吗?这是故意的行为吗?如果是这样,有没有办法防止这种行为?

谢谢

1 个答案:

答案 0 :(得分:2)

实例open method记录为:

  

使用模式r+打开或重新打开文件。

这意味着您无法依赖该方法以正确的方式打开它。这不是什么大问题,因为Tempfile的正常使用是不同的:

tmp = Tempfile.new('test.bin', Dir.getwd)
File.open('test.bin', 'rb') { |h| IO.copy_stream(h, tmp) } # => 2
tmp.rewind

现在,一旦它被“重绕”,你就可以从头开始读取你想要的任何数据。