From: Robert Klemme Date: 2005-03-22T22:59:53+09:00 Subject: Re: Reading and writing a binary file "Chris G�nther" schrieb im Newsbeitrag news:42400070.2050609@gmx.de... > Thanks Robert, > > you are absolutely right with your remarks using a block. The code I > posted was just a small copied fraction of the real code, in which I > cannor use a block because the same fd will be stored in a hash for > later usage by another method. > Anyway, meanwhile I found the cause of this problem (again you are > right, it was not in the code I posted) , but now I have another related > problem that tricks my mind. 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?? > > > > Thanks again in advance, > Chris > > > > > > #!/usr/bin/env ruby > > FNAME, FSIZE, OFFSET, VALUE = 'foooo.dat', 1024, 32, > [?c,?a,?f,?e].pack('cccc') > > File.open(FNAME,"ab+") {|fd| > fd.pos=0 > bin_data = [0].pack('c')*FSIZE > fd.write(bin_data) > } > > File.truncate(FNAME,FSIZE) > > File.open(FNAME,"ab+") {|fd| > fd.pos=0 > data=fd.read(FSIZE) > data[OFFSET,VALUE.length]=VALUE > fd.pos=0 > fd.write(data) > p "written modified piece of data = '#{data[OFFSET,VALUE.length]}'" > } You truncate too often: > File.truncate(FNAME,FSIZE) > File.open(FNAME,"ab+") {|fd| > fd.pos=OFFSET > patched=fd.read(VALUE.length) > p "read modified piece of data = '#{patched}'" > puts "Oooops !!!" unless VALUE==patched > } Careful when you're copying and pasting. Regards robert