That will work well for small to moderately sized files: anything that fits in memory, which is quite large these days.It is a good solution in many cases.
An advantage of writing to a temporary file and renaming is that you are less likely to end up with a truncated or partial file replacing your original. With your method, if your program or the system fails after you open the file for output, which truncates it, and before you finish writing and flushing all your buffers to disk, you will end up with an incomplete file. If you write to a temporary file and only rename it after closing your output file handle the risk of ending up with a truncated file is much much less.
There is still some risk, even if you write a temporary file, close and rename it. You can reduce the risk further, but not to zero as far as I can tell. Through the various layers of control between your program and the persistent storage medium, it is possible that operations are re-ordered and that abrupt termination (e.g. power loss) can result in corruption despite even extreme measures taken in your program. http://www.gossamer-threads.com/lists/perl/porters/236839 is one writeup on some of these issues.
In reply to Re^3: In place editing of text files
by ig
in thread In place editing of text files
by jevaly
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |