2017-07-11 57 views
0

经过大量的挖掘后,我发现RubyZip可以破坏二进制文件。仔细看后,好像Tempfile类无法正确重新打开二进制文件。为了演示效果采取以下脚本:Ruby文件损坏的二进制文件

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文件我使用只包含两个字节:00 1a。临时文件损坏后,它包含1个字节:00。如果有关系,我正在运行windows。

有什么,我失踪?这是故意的行为吗?如果是这样,是否有办法阻止这种行为?

谢谢

回答

2

实例open method记录为:

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

这意味着您不能依赖该方法以正确的模式打开它。这不是一个大问题,因为在正常使用的将它视为是不同的:

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

现在一旦它被“倒带”你可以阅读你从它从一开始就开始想要的任何数据。