Skip to content

file.rename(): Guaranteed to be complete or not at all?

3 messages · Brian Ripley, Henrik Bengtsson

#
Hi,

assume I have an existing file 'pathname' and I want to rename it to
'pathnameN' (which does not exist).  I use:

res <- file.rename(pathname, pathnameN);

Is it guaranteed that:

(1) if res == TRUE, the file now have name 'pathnameN' and there is no
file with name 'pathname'?
(2) if res == FALSE, nothing has changed?

or could it theoretically also be the case that

(3) there are say two identical files named 'pathname' and 'pathnameN',
(4) or worse, that neither exists?

I can see how (3) could happen if the file is renamed by first using
file.copy() and then file.remove() while there is lack of write/delete
permission for the latter.

Currently, my code asserts that (3) and (4) did not happen.  Is that
unnecessary - does file.rename() do that for me (regardless of OS)?

Thanks

Henrik
#
As the help says:

   This is subject to the limitations of the OS's corresponding system
   call: ....

E.g. on Fedora 14 'man 2 rename' says, inter alia,

'If newpath already exists it will be atomically replaced (subject to 
a few conditions; see ERRORS below), so that there is no point at 
which another process attempting to access newpath will find it 
missing.

However, when overwriting there will probably be a window in which 
both oldpath and newpath refer to the file being renamed.

BUGS

On NFS file systems, you can not assume that if the operation failed 
the file was not renamed.'

and for Windows see

http://msdn.microsoft.com/en-us/library/aa365240%28v=vs.85%29.aspx

where R uses flags (MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED 
| MOVEFILE_WRITE_THROUGH)

Windows 95 was an example of an OS which could delete the 'to' file 
and fail to move 'from'.
On Tue, 1 Mar 2011, Henrik Bengtsson wrote:

            

  
    
#
Thank you very much for these pointers.

In order to lower the risk for proceeding unknowingly with (3) or (4),
I'll keep my post-rename tests for them (understanding that it is
still not bullet proof).

/Henrik

On Tue, Mar 1, 2011 at 11:01 PM, Prof Brian Ripley
<ripley at stats.ox.ac.uk> wrote: