# Write to the top of a file

**URL:** <https://www.ruby-forum.com/t/write-to-the-top-of-a-file/188891>\
**Category:** Ruby\
**Created:** [May 19, 2010, 11:27pm UTC](https://www.ruby-forum.com/t/write-to-the-top-of-a-file/188891 "2010-05-19T23:27:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [May 19, 2010, 11:27pm UTC](https://www.ruby-forum.com/t/write-to-the-top-of-a-file/188891/1 "2010-05-19T23:27:59Z")

</div>

Hi,

I want to write some content to an existing file and I want to new  
content be the first line of the file. How to do that?

Thanks

---

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [May 20, 2010, 12:25am UTC](https://www.ruby-forum.com/t/write-to-the-top-of-a-file/188891/2 "2010-05-20T00:25:58Z")

</div>

On 19/05/2010 22:28, John Wu wrote:

> Hi,
> 
> I want to write some content to an existing file and I want to new  
> content be the first line of the file. How to do that?

Hi John,

You can’t do it directly - there is no insert for disk files. What you  
have to do depends how big it is.

For file that will fit in RAM, load it, join with your first line, and  
save it all.

For larger files, you need to copy and rename.

Regards

Ian

---

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [May 20, 2010, 1:26am UTC](https://www.ruby-forum.com/t/write-to-the-top-of-a-file/188891/3 "2010-05-20T01:26:16Z")

</div>

On Wednesday, May 19, 2010 05:25:13 pm Ian H. wrote:

> On 19/05/2010 22:28, John Wu wrote:
> 
> > Hi,
> > 
> > I want to write some content to an existing file and I want to new  
> > content be the first line of the file. How to do that?  
> > [snip]  
> > For file that will fit in RAM, load it, join with your first line, and  
> > save it all.
> 
> For larger files, you need to copy and rename.

Or for files whose contents you actually care about – and many of those  
are  
small files. Think about what happens if you crash.

The typical method is to create a temporary file, insert the data,  
append the  
original file, then rename on top of the original file. Then the file is  
never  
in a corrupted state, even temporarily.
