File#truncate fills file with zeros

Hello!

Running this following code:

f = File.open(filename, 'w')
f.truncate(10)
f.close

leaves the file filled with 10 zero bytes. Its pretty unexpected,
since the documentation makes no mention of this
(http://ruby-doc.org/core/classes/File.html#M002539).

File.truncate(filename, 10)

works fine, leaving any pre-existing bytes intact. Looking at the
example I assume this has to do with the File#truncate method
expecting me to write some bytes and then truncate them.

Just putting this out there for the next confused person since Google
made no mention of this!

this is because opening a file with "w" truncates it.

···

On Wed, 2010-11-17 at 06:33 +0900, Leslie Viljoen wrote:

Hello!

Running this following code:

f = File.open(filename, 'w')
f.truncate(10)
f.close

leaves the file filled with 10 zero bytes. Its pretty unexpected,
since the documentation makes no mention of this
(class File - RDoc Documentation).

File.truncate(filename, 10)

works fine, leaving any pre-existing bytes intact. Looking at the
example I assume this has to do with the File#truncate method
expecting me to write some bytes and then truncate them.

Just putting this out there for the next confused person since Google
made no mention of this!

aaaaaaaaah!

···

On Wed, Nov 17, 2010 at 12:07 AM, niklas | brueckenschlaeger <niklas@brueckenschlaeger.de> wrote:

this is because opening a file with "w" truncates it.