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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.