From: 7stud -- Date: 2009-05-02T17:29:21+09:00 Subject: Re: Read and re-write file with one open? 7stud -- wrote: > Adam Bender wrote: >> On Fri, May 1, 2009 at 4:33 PM, James Dinkel 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? Hmmm...I guess you are left with a file that you can examine and then locate the spot where you should begin gsub'ing again. You may however run into a problem if the program crashes in the middle of a line. Input and output to/from files gets buffered to make things more efficient because repeatedly accessing files is relatively slow. For instance, when you tell your program to write a line to a file, it doesn't actually do that. Instead, programs store the line in a buffer. Then when the buffer fills up, the contents of the buffer get written to the file in one big chunk. That cuts down on the number of file accesses. The same thing happens when you read from a file. You may tell your program to read one line from a file, but your program will ignore you. Instead, your program will read a chunk of the file and store it in a buffer. Then If you request more lines from the file, your program will retrieve them from the buffer. That cuts down on the number of times your program has to access the file. As a result, I think even though you may write one line at a time to the file, it's possible the buffer may get written to the file where the last thing in the buffer is half a line. Then if your program crashes you are going to have a corrupted line in your file. -- Posted via http://www.ruby-forum.com/.