Here is a simple C program for illustration:
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
//MoveFile(argv[0], "dst.exe");
getchar();
return 0;
}
make an test.exe from code above.
Now execute test.exe, the test.exe hangs there due to getchar(), then I can cut and paste this exe freely.
But when I uncomment that MoveFile(argv[0], "dst.exe");
, I was hoping it could move itself to dst.exe, it turns out to have a dst.exe, while program.exe is still there, just like CopyFile()
does.
From what I know, in Windows, when exe is running I can rename it, move it, but not deleting it, that MoveFile()
behaves as a combination of CopyFile()
and DeleteFile()
And also see this from Microsoft doc MoveFileEx.
BOOL WINAPI MoveFileEx(
_In_ LPCTSTR lpExistingFileName,
_In_opt_ LPCTSTR lpNewFileName,
_In_ DWORD dwFlags
);
dwFlags has an option MOVEFILE_COPY_ALLOWED
the file is to be moved to a different volume, the function simulates the move by using the CopyFile and DeleteFile functions. If the file is successfully copied to a different volume and the original file is unable to be deleted, the function succeeds leaving the source file intact. This value cannot be used with MOVEFILE_DELAY_UNTIL_REBOOT.
Further confirming my guess, and I tested with MoveFileEx()
with option MOVEFILE_REPLACE_EXISTING
, recompiled the program, run it, now MoveFileEx()
just returned as fail, not even dst.exe generated.
But I can definitely cut and paste that exe while running, MoveFileEx()
should does so, why???
If they can't, what should I do to make it just like cut and paste.
MoveFile
returns a success/failure indicator, that you should check. If it fails you should useGetLastError
to see why it failed.argv[0]
is the executable name or accessible. It's just parsed out of the command line that the parent passed toCreateProcess
. It could be unrelated to the actuallpApplicationName
that was used, or it could be related but the parent set an unrelated working directory in the child. You have to callGetModuleFileNameW(NULL, lpFilename, nSize)
. Note that this is the [W]ide character (Unicode) version. Never use ANSI for filesystem paths; that's a legacy from Windows 9x and MS-DOS. You should also be usingwmain
instead ofmain
to get the Unicode command line.