Win32 API for rename a file in C

2020-06-16 04:23发布

问题:

If the source directory and the target directory, MoveFile would actually make a copy of the source file into the target file, which means that I will end up seeing two files.

Is that the best way that rename can be achieved?

回答1:

The MoveFile function is indeed what you want. From the documentation:

The MoveFile function will move (rename) either a file or a directory (including its children) either in the same directory or across directories.

If the source and destination locations are both on the same volume, then an atomic rename operation is performed. If they're on different volumes, then a copy/delete operation is done instead (this is the best you can do).



回答2:

Try

#include <stdio.h>

int Result = rename( oldname , newname );

if (Result)
   // "Error occurred." );
else
   // "File was successfully renamed!";


回答3:

You might want to try using the MoveFileEx() API without specifying the MOVEFILE_COPY_ALLOWED to see if that provides the behavior you're looking for.



回答4:

What does your code look like? I have this:

if(MoveFile(_T("c:\\hold\\source"),_T("c:\\hold\\dest")))
{
    printf("succeeded\n");
}else
{
    printf("Error %d\n",GetLastError());
}

and it does not leave the source behind.