tom
tom

Reputation: 14513

Win32 API for rename a file in C

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?

Upvotes: 10

Views: 25258

Answers (4)

cpx
cpx

Reputation: 17557

Try

#include <stdio.h>

int Result = rename( oldname , newname );

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

Upvotes: 4

weloytty
weloytty

Reputation: 6098

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.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 993045

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).

Upvotes: 11

Michael Burr
Michael Burr

Reputation: 340198

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.

Upvotes: 0

Related Questions