Erasing text from a file

L

Lucas L.

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
 
A

Andrea Fazzi

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 }
 
S

Sebastian Hungerecker

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
 
A

Andrea Fazzi

Sebastian Hungerecker ha scritto:
The "file = nil" part is completely unneccessary. You can just do
File.open('file.txt', 'w') {}

Ok, thank you :)

Andrea
 
T

ts

Lucas said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top