用红宝石写入文件的中间 [英] writing to the middle of a file in ruby

查看:105
本文介绍了用红宝石写入文件的中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆