Adam Bender wrote:
> On Fri, May 1, 2009 at 4:33 PM, James Dinkel <jdinkel / gmail.com> wrote:
> 
>>  end
>>
>> This opens a file for reading and writing, reads the file into an array,
>> then you modify the array how you need to.  Then the block returns to
>> the beginning of the file, writes out your changes over the existing
>> file, then chops off what's left.  Then, of course, the file is closed
>> when the block exits.
>>
> 
> This is exactly what I wanted.  Thanks everyone.
> 
> Adam

I think you guys are missing the point.   There are lots of ways to 
rewrite a file that 'work'. For instance, simply reading a file into an 
array, closing the file, then opening the file for writing(which erases 
the file), and then writing the altered lines back to the file 'works'. 
You can test it yourself and see that it works.  You can rewrite the 
file like that 1,000 times and it will 'work'.

However, if your data is important you need to ask yourself the 
question: what happens if my program crashes while I am writing the data 
back out to the file?

So let's ask that question about the solution you've decided to adopt. 
Suppose your program is at the point where it has written half of the 
altered data back to the file, and the file contains half altered data 
and half original data.  Then your program crashes.  What are you left 
with?

The "rewriting a file" issue has been hashed out by many programmers for 
decades.  You can either try to come up with your own screwy method, or 
you can adopt an accepted idiom.  Within the accepted idiom, modules 
like Tempfile were created to deal with the problem of overwriting an 
existing file name, and it provides a shortcut.

>truncate: Not available on all platforms.

That should also be a red flag.  Generally, you should strive to write 
cross platform programs.






-- 
Posted via http://www.ruby-forum.com/.