Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Erasing text from a file

0 views
Skip to first unread message

Lucas L.

unread,
May 11, 2008, 6:56:48 AM5/11/08
to
To me it seems it should be a rather obvious thing, but no matter where
I look, I can't find how to erase text from a file or clear a file. The
only things I have found are moving the the cursor to the start and
writing more text over it (but that doesn't get rid of it), or reopening
the file.

Is there a way to simple erase text from the file?

Thanks,
Lucas
--
Posted via http://www.ruby-forum.com/.

Andrea Fazzi

unread,
May 11, 2008, 7:20:42 AM5/11/08
to
Lucas L. ha scritto:

> To me it seems it should be a rather obvious thing, but no matter where
> I look, I can't find how to erase text from a file or clear a file. The
> only things I have found are moving the the cursor to the start and
> writing more text over it (but that doesn't get rid of it), or reopening
> the file.
>
> Is there a way to simple erase text from the file?
>
> Thanks,
> Lucas
>

File.open('file.txt', 'w') { |file| file = nil }


Lucas L.

unread,
May 11, 2008, 8:14:30 AM5/11/08
to
Andrea Fazzi wrote:
> File.open('file.txt', 'w') { |file| file = nil }

That reopens the file. Is there a way to do it without reopening?

Sebastian Hungerecker

unread,
May 11, 2008, 8:34:35 AM5/11/08
to
Lucas L. wrote:
> Andrea Fazzi wrote:
> > File.open('file.txt', 'w') { |file| file = nil }

The "file = nil" part is completely unneccessary. You can just do


File.open('file.txt', 'w') {}

> Is there a way to do it without reopening?

I don't think there is.

HTH,
Sebastian
--
NP: Depeche Mode - Freestate
Jabber: sep...@jabber.org
ICQ: 205544826

Andrea Fazzi

unread,
May 11, 2008, 9:18:43 AM5/11/08
to
Sebastian Hungerecker ha scritto:

> Lucas L. wrote:
>
>> Andrea Fazzi wrote:
>>
>>> File.open('file.txt', 'w') { |file| file = nil }
>>>
>
> The "file = nil" part is completely unneccessary. You can just do
> File.open('file.txt', 'w') {}
>
>

Ok, thank you :-)

Andrea


ts

unread,
May 11, 2008, 9:29:45 AM5/11/08
to
Lucas L. wrote:
> Is there a way to simple erase text from the file?

perhaps File#truncate

---------------------------------------------------------- File#truncate
file.truncate(integer) => 0
------------------------------------------------------------------------
Truncates _file_ to at most _integer_ bytes. The file must be
opened for writing. Not available on all platforms.

f = File.new("out", "w")
f.syswrite("1234567890") #=> 10
f.truncate(5) #=> 0
f.close() #=> nil
File.size("out") #=> 5

Guy Decoux


Lucas L.

unread,
May 11, 2008, 9:19:56 PM5/11/08
to
ts wrote:
> perhaps File#truncate

The documentation says this is platform specific, which I'd like to
avoid.
File.open will have to do.

0 new messages