2017-07-11 58 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 

現在一旦它被「倒帶」你可以閱讀你從它從一開始就開始想要的任何數據。