It's a bit easier if you can co-operate with the other programs that might create files there.

Anyway, here's one solution that can work if the other programs don't co-operate (of course, the other programs can be very badly behaved, and overwrite your files by force :), even on NFS.

First, create a new empty directory in the destination directory. We assume that only you will use this directory, and other programs won't create files in it. Then copy the file into that directory with an arbitary name. Than create a symlink in the original directory with the name you are planning to use as the name of the old file eventually. Creating a symlink doesn't overwrite an existing file (not even a symlink), but rather fail in that case. If that happens, choose a new name. Then, rename the copied file from inside the directory to the same name as this symlink. This will overwrite the symlink, but do it atomically: the name will never cease to exist. Finally, remove the directory.

(If you want to copy a directory, this won't work, but that case is simpler anyway, as directory creation won't overwrite anything anyway.)

Update: there are existing functions (not neccessarily perl) that create unique temporary files. Try looking at their sources to see what they do.

Update: it might be simpler to just create a file with the mknod syscall, because that doesn't overwrite an existing file. Then, you don't have to move anything. That works through NFS too (although I didn't test whether it was really atomic), but it might not work on all systems.


In reply to Re: How to move/copy a file without overwriting an existing file by ambrus
in thread How to move/copy a file without overwriting an existing file by bart

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.