http://www.perlmonks.org?node_id=1178449


in reply to Re^6: Read in hostfile, modify, output
in thread Read in hostfile, modify, output

From the perl 5.24.0 C sources, file win32.c:

DllExport int win32_rename(const char *oname, const char *newname) { char szOldName[MAX_PATH+1]; BOOL bResult; DWORD dwFlags = MOVEFILE_COPY_ALLOWED; dTHX; if (stricmp(newname, oname)) dwFlags |= MOVEFILE_REPLACE_EXISTING; strcpy(szOldName, PerlDir_mapA(oname)); bResult = MoveFileExA(szOldName,PerlDir_mapA(newname), dwFlags); if (!bResult) { DWORD err = GetLastError(); switch (err) { case ERROR_BAD_NET_NAME: case ERROR_BAD_NETPATH: case ERROR_BAD_PATHNAME: case ERROR_FILE_NOT_FOUND: case ERROR_FILENAME_EXCED_RANGE: case ERROR_INVALID_DRIVE: case ERROR_NO_MORE_FILES: case ERROR_PATH_NOT_FOUND: errno = ENOENT; break; case ERROR_DISK_FULL: errno = ENOSPC; break; case ERROR_NOT_ENOUGH_QUOTA: errno = EDQUOT; break; default: errno = EACCES; break; } return -1; } return 0; }
we see that the Perl rename function on Windows is implemented using the Win32 MoveFileEx function.

Here is a standalone C program using the Win32 MoveFileEx function:

// movetest.cpp // compile with: CL /W3 /MD movetest.cpp // example run: movetest fromfile tofile #include <windows.h> #include <stdio.h> int main(int argc, char* argv[]) { if (argc != 3) { fprintf(stderr, "usage: movetest file1 file2\n"); return 1; } char* from = argv[1]; char* to = argv[2]; fprintf(stderr, "move '%s' to '%s'...", from, to); if (!MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)) { fprintf(stderr, "failed: error=%lu\n", (unsigned long)GetLastErr +or()); return 2; } fprintf(stderr, "done.\n"); return 0; }
After compiling, you can run with:
movetest newfile.txt originalfile.txt
which overwrites the original file even if it already exists (if you have permission to do so).

Well, it's pleasing to see that Perl is doing the rename via a single Win32 MoveFileEx function call in preference to a DeleteFile followed by a MoveFile (which would have no chance of being atomic). However, the jury seems to be out on how truly atomic Windows rename is. After reading this stackoverflow question I'm still confused. Alternatives to MoveFileEx appear to be ReplaceFile and MoveFileTransacted.

Via brute force search of the perl 5.24.0 source code, I further noticed that MoveFileEx is also available to Perl code via the Win32API::File module. In the latest Perl distribution, Win32API::File::MoveFileEx is called by ExtUtils::Install.