Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
how to write in the middle of a file
Roger Pack
6/26/2008 1:00:00 AM
Greetings all. For some reason the answer to this stumps me.
Say I have an existing file, 1K long, and I want to write something
right in the middle of it, without changing the file size.
I would have thought that
a = File.open 'file', 'a+'
a.seek 500
a.write 'abc'
a.close
would work but doesn't seem to. Thoughts?
-R
--
Posted via
http://www.ruby-...
.
2 Answers
Rob Biedenharn
6/26/2008 2:39:00 AM
0
On Jun 25, 2008, at 8:59 PM, Roger Pack wrote:
> Greetings all. For some reason the answer to this stumps me.
> Say I have an existing file, 1K long, and I want to write something
> right in the middle of it, without changing the file size.
meaning you want to OVERWRITE something in the middle, yes?
>
> I would have thought that
> a = File.open 'file', 'a+'
> a.seek 500
> a.write 'abc'
> a.close
>
> would work but doesn't seem to. Thoughts?
> -R
Try a mode of 'r+'. The 'a' part says you want all the writes to go
the the end-of-file (whatever that happens to be at the time).
File.open 'file', 'w' do |f| f.write 'x'*1024 end
a = File.open 'file', 'r+'
a.seek 500
a.write 'abc'
a.close
all = File.read('file')
irb> puts all.size
1024
=> nil
irb> puts all.index('abc')
500
=> nil
You can puts(all) yourself if you want ;-)
-Rob
Rob Biedenharn
http://agileconsult...
Rob@AgileConsultingLLC.com
Roger Pack
6/26/2008 2:42:00 AM
0
> Try a mode of 'r+'. The 'a' part says you want all the writes to go
> the the end-of-file (whatever that happens to be at the time).
Works like a charm. You rock!
-R
--
Posted via
http://www.ruby-...
.
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
how to write in the middle of a file
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password