# How to write in the middle of a file

**URL:** <https://www.ruby-forum.com/t/how-to-write-in-the-middle-of-a-file/141465>\
**Category:** Ruby\
**Created:** [June 26, 2008, 3:01am UTC](https://www.ruby-forum.com/t/how-to-write-in-the-middle-of-a-file/141465 "2008-06-26T03:01:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![rogerdpack](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/45deac/32.png) [@rogerdpack](https://www.ruby-forum.com/u/rogerdpack)\
**Post date:** [June 26, 2008, 3:01am UTC](https://www.ruby-forum.com/t/how-to-write-in-the-middle-of-a-file/141465/1 "2008-06-26T03:01:39Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![rogerdpack](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/45deac/32.png) [@rogerdpack](https://www.ruby-forum.com/u/rogerdpack)\
**Post date:** [June 26, 2008, 4:41am UTC](https://www.ruby-forum.com/t/how-to-write-in-the-middle-of-a-file/141465/2 "2008-06-26T04:41:42Z")

</div>

On Jun 25, 2008, at 8:59 PM, Roger P. 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 B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![rogerdpack](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/45deac/32.png) [@rogerdpack](https://www.ruby-forum.com/u/rogerdpack)\
**Post date:** [June 26, 2008, 4:43am UTC](https://www.ruby-forum.com/t/how-to-write-in-the-middle-of-a-file/141465/3 "2008-06-26T04:43:47Z")

</div>

> 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
