简体   繁体   中英

Ruby tempfile corruption of binary files

after a lot of digging around I've found that RubyZip can corrupt binary files. After taking a closer look, it seems like Tempfile class can't correctly re-open binary files. To demonstrate the effect take the following script:

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

The test.bin file I'm using only contains two bytes: 00 1a . After corruption of the temporary file, it contains 1 byte: 00 . If it matters I'm running windows.

Is there something that I'm missing? Is this intentional behavior? And if so, is there a way to prevent this behavior?

Thank you

The instance open method is documented as:

Opens or reopens the file with mode r+ .

This means you can't depend on that method to open it in the correct mode. That's not a big deal since the normal use of Tempfile is different:

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

Now once it's been "rewound" you can read any data you want from it starting from the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM