"Chris Guenther" <chris_guenther / freenet.de> schrieb im Newsbeitrag news:d1mhu3$bi6$1 / news.mch.sbs.de... > Hi, > > I am having trouble reading values from an existing (or maybe not yet > exisiting) binary file: > My target is to open a binary file for reading and writing (if it does not > exisit it should be created). > If the file was not yes existing I'd like to fill it with binary data to a > certain predefined size. > Later on I'd like to position my file position, and read and write whatever > I like. > > The following piece does not work as intended: > > require 'pp' > UNDER_UNIX = CONFIG['target_os'].to_s.index('linux')!=nil > filename='foo.bin' > size=1024 > dont_write=FileTest.exists?(filename) && File.stat(filename).size==size > begin > fd=File.open(filename,"ab+") > fd.binmode unless UNDER_UNIX # assuming !UNIX=WINDOWS > rescue => e > pp e > fd=File.open(filename,"wb+") > puts "opened #{filename} with 'wib+'" > end > > fd.sync=true > fd.seek(0) > unless dont_write > bin_data = [0].pack('c')*(size) > fd.write(bin_data) > # OK now I really have a file of size 1024 with a binay 0 contents > end > > ###.... then sometime later using the same file descriptor (fd) : > requestes_stream_position = 900 > fd.pos=(requestes_stream_position) > p "tell=#{fd.tell}" > # Now please read 30 binary 0s into a binary string > bin_value=fd.read(30) > > #### I ASSUMED THAT bin_value now is a "binary string of size 30", but > unfortunately it is nil !!! > > > > Thanks in adcance, > C. I don't know what you're doing wrong. Your script works fine for me. Btw, you don't close the fd. Here's how I'd do it: filename='foo.bin' size=1024 File.open(filename, "ab+") do |fd| fd.seek(0, IO::SEEK_END) if fd.tell < size fd.seek 0 fd.write( "\000" * size ); elsif fd.tell > size # if you need the file to be exact this size fd.truncate size end requestes_stream_position = 900 fd.seek requestes_stream_position bin_value = fd.read(30) p bin_value end Notes: - don't change binmode depending on platform, always use "b" for binary files. - use File.open with block for proper close / cleanup Kind regards robert