tags:

views:

186

answers:

1

I've opened a file in ruby with the options a+. I can seek to the middle of the file and read from it but when I try to write the writes always go to the end. How do I write to a position in the middle?

jpg = File.new("/tmp/bot.jpg", "a+")
jpg.seek 24
puts jpg.getc.chr
jpg.seek 24
jpg.write "R" 
jpg.seek 28
jpg.write "W" 
puts jpg.pos
jpg.close

The R and W both end up at the end of the file.

I know I can only overwrite existing bytes, that is ok, that is what I want to do.

+5  A: 

This behavior is exactly what you request with the "a+" mode: ensure all writes always go to the end, while allowing reading and seeking (seeking only meaningful for reading of course, given the mode). Use "r+" if you don't want all writes to always go to the end.

Alex Martelli