用红宝石写入文件的中间 [英] writing to the middle of a file in ruby
问题描述
我用a +选项打开了一个红宝石文件。我可以找到文件的中间并从中读取,但是当我尝试写入文件时,总是进行到最后。
jpg = File.new(/ tmp / bot.jpg,如何写入中间位置? a +)
jpg.seek 24
puts jpg.getc.chr
jpg.seek 24
jpg.writeR
jpg.seek 28
jpg.writeW
puts jpg.pos
jpg.close
< R和W都在文件末尾。
我知道我只能覆盖现有的字节,没关系,那就是我想要的 c>模式:确保所有的写入操作总是进行到最后,同时允许读取和查找(当然,在给定模式的情况下,只对读取有意义)。使用r +
,如果您不希望所有的写入操作都一直到最后。
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.
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.
这篇关于用红宝石写入文件的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!