how to write in the middle of a file

R

Roger Pack

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
 
R

Rob Biedenharn

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://agileconsultingllc.com
(e-mail address removed)
 
R

Roger Pack

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top