Adam Bender
4/30/2009 7:12:00 AM
[Note: parts of this message were removed to make it a legal post.]
On Thu, Apr 30, 2009 at 1:26 AM, 7stud -- <bbxx789_05ss@yahoo.com> wrote:
> Yes, opening the file in write mode! However, you are going to expose
> yourself to this catastrophe. Suppose you read the contents of the
> file into a variable, then open the file for writing, which then erases
> the file, but immediately thereafter your program crashes or the power
> goes out in your city.
>
> So the idiom for rewriting a file is:
>
> 1) Open the file for *reading*.
> 2) Open another file for writing with a name like origName-edited.txt
> 3) Read the original file line by line(saves memory, but is slower)
> 4) Write each altered line to the file origName-edited.txt
> 5) Delete the original file.
> 6) Change the name of the new file (origName-edited.txt) to origName.txt
I see the potential for catastrophe with the way I suggested, however, there
is potential for catastrophe here if there is already an
"origName-edited.txt" file (I know, slim chance, but you never know). You
could get around this by generating new file names until you found one that
didn't exist, or writing to /tmp, of course. I think I'll switch to Greg
Brown's suggestion. Does Tempfile guarantee that it won't overwrite an
existing file?
Adam