开发者

writing to the middle of a file in ruby

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开发者_JS百科", "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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜