# File.write bug

**URL:** <https://www.ruby-forum.com/t/file-write-bug/84742>\
**Category:** Ruby\
**Created:** [February 7, 2007, 1:48pm UTC](https://www.ruby-forum.com/t/file-write-bug/84742 "2007-02-07T13:48:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![wouter](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/e99b99/32.png) [@wouter](https://www.ruby-forum.com/u/wouter)\
**Post date:** [February 7, 2007, 1:48pm UTC](https://www.ruby-forum.com/t/file-write-bug/84742/1 "2007-02-07T13:48:34Z")

</div>

Hello all,

I’m relatively new to ruby and I think I’ve found a bug. It doesn’t  
seem to be in my code.

I written this test script:

# test.rb

File.open(“blaat.txt”,“w”) do |f|  
f.write “test\r\n”  
f.write “test\r”  
f.write “test\n”  
end  
############################

And it produces unexpected results. It seems to insert a “\r” before  
every “\n”. I have included the result of this script on my computer.

I’m running Windows XP SP2 and ruby 1.8.5.

Does anyone know what the problem could be and how to fix it?

Wouter S.

---

<div class="post-metadata">

**Author:** ![wouter](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/e99b99/32.png) [@wouter](https://www.ruby-forum.com/u/wouter)\
**Post date:** [February 7, 2007, 2:45pm UTC](https://www.ruby-forum.com/t/file-write-bug/84742/2 "2007-02-07T14:45:39Z")

</div>

On Feb 7, 5:48 am, “Wouter S.” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> f.write “test\r”
> 
> Wouter S.
> 
> [blaat.txt]test  
> test test

It’s not a bug.

On Windows, “\n” evaluates to a carriage return and a line feed, what  
you may be used to calling “\r\n”. If you open blaat.txt in SciTE (or  
any similar text editor) and view the ends of lines (View → End of  
Line), you’ll see.

So what’s happening is that f.write “test\r\n” is writing a carriage  
return, then “\n” which is a carriage return and a line feed.

---

<div class="post-metadata">

**Author:** ![wouter](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/e99b99/32.png) [@wouter](https://www.ruby-forum.com/u/wouter)\
**Post date:** [February 7, 2007, 3:27pm UTC](https://www.ruby-forum.com/t/file-write-bug/84742/3 "2007-02-07T15:27:47Z")

</div>

On 2/7/07, Chris S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> > f.write “test\r\n”  
> > Does anyone know what the problem could be and how to fix it?  
> > any similar text editor) and view the ends of lines (View → End of  
> > Line), you’ll see.
> 
> So what’s happening is that f.write “test\r\n” is writing a carriage  
> return, then “\n” which is a carriage return and a line feed.

…and if you don’t like the behaviour, use File.open(‘xxxx’, ‘wb’) -  
notice the ‘b’.  
Or specify mode as IO::WRONLY | IO::BINARY

The same works for Python as well.
