Is file.rename() atomic?

John Colvin john.loughran.colvin at gmail.com
Thu Dec 12 11:17:53 PST 2013


On Thursday, 12 December 2013 at 17:08:13 UTC, Jacek 
Furmankiewicz wrote:
>    void rename(in char[] from, in char[] to);
>         Rename file from to to. If the target file exists, it 
> is overwritten.
>
>         Throws:
>         FileException on error.
>
> Just wanted to know if this operation is atomic?
> or does it depend on the underlying file system?
>
> In short, in the file nanoseconds/milliseconds that this 
> operation is occurring is it possible for someone else to be 
> reading the same file and get a dirty read (i.e. with only half 
> of the contents overriden, etc)?
>
> Thanks

Here's the implementation,as you can see it's just c function 
calls, no work is done in D:

void rename(in char[] from, in char[] to)
{
     version(Windows)
     {
         enforce(MoveFileExW(std.utf.toUTF16z(from), 
std.utf.toUTF16z(to), MOVEFILE_REPLACE_EXISTING),
                 new FileException(
                     text("Attempting to rename file ", from, " to 
",
                             to)));
     }
     else version(Posix)
         cenforce(core.stdc.stdio.rename(toStringz(from), 
toStringz(to)) == 0, to);
}


On a posix compliant system, I'm pretty sure this is guaranteed 
to be atomic as far as any other process is concerned. On 
windows, I don't know. A quick google suggests that there may 
have been a C or filesystem bug on OSX with regards to this.


More information about the Digitalmars-d-learn mailing list