From: "Chris Günther" Date: 2005-03-24T01:49:48+09:00 Subject: Re: Reading and writing a binary file Pit Capitain wrote: > Chris G�nther schrieb: > >> ... I am trying to patch binary data in a file. >> Unfortunately the data I am patching is not the data I get when >> reading it back from the patched binary file. >> Any ideas?? >> ... >> File.open(FNAME,"ab+") {|fd| >> fd.pos=0 >> ... > > > Hi Chris, > > it seems that the mode "ab+" is your problem. According to [1], "a+" > means open the file for reading and writing, starting at the end of the > file. This also means (at least on windows), that the end of file is > position 0. So what you are doing above is writing the patched data > after the end of the original file. > > For patching a binary file I'd change your code to: > > FNAME, FSIZE, OFFSET, VALUE = 'foooo.dat', 1024, 32, > [?c,?a,?f,?e].pack('cccc') > > # "wb+" for initial data: truncate existing content > File.open(FNAME,"wb+") {|fd| > bin_data = [0].pack('c')*FSIZE > fd.write(bin_data) > } > > # "rb+" for the patch: open at the beginning > File.open(FNAME,"rb+") {|fd| > fd.pos=OFFSET > fd.write(VALUE) > p "written modified piece of data = '#{VALUE}'" > } > > # "rb" for reading the data > File.open(FNAME,"rb") {|fd| > fd.pos=OFFSET > patched=fd.read(VALUE.length) > p "read modified piece of data = '#{patched}'" > puts "Oooops !!!" unless VALUE==patched > } > > Regards, > Pit > > [1] http://www.ruby-doc.org/core/classes/IO.html > > Hi Pit, thanks for your contribution. That's exactly the solution I already have. What I dont like about this solution is that you have to open and close file descriptors 3 times just for patching one little file (For sure a working solution but quite some overhead). Just for academical reason it seeems I have to fall back reading the C-sources :-( to find out what is going wrong under the hood. Chris