Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MoveFile Function

Status
Not open for further replies.

Ati2ude

Programmer
Dec 11, 2001
79
US
Has anyone ever used the MoveFile function to move an entire directory? I can use the function to move a single file at a time, but MSDN states that the function will move an entire directory including children.

Any help would be great!!

Thanks in advance.
Ati2ude
 
On MSDN You can find:
1. The one caveat is that the MoveFile function will fail on directory moves when the destination is on a different volume.
2. The MAPI version of the MoveFile function won't move a directory. This function always works across drives, and it always performs a copy operation then deletes the original file, as opposed to truly performing a move operation.

It is better to use CopyFile() for moving files in directories (You must then use FinFirstFile(), CreateDirectory() etc., but it works allways).
 
tchouch,

You are absolutely correct. My feeling is that MSDN is mis-leading here. So I wrote a function that will move a entire directory recursively.

The only caveat here is that you do not want to move the folder to the same path.

I have posted the code for anyone else they may have the same problem.

Ati2ude


HANDLE dir;
WIN32_FIND_DATA fd;
HINSTANCE inst;
char sOldFileName[255];
char sNewFileName[255];
char sOldDirName[255];
char sNewDirName[255];


if (!FileExists(sOldPath))
return FALSE;


if (CreateFolderBuildTree(sNewPath.GetBuffer (sNewPath.GetLength())) == -1)
return FALSE;

strcpy(sOldDirName, sOldPath);
strcat(sOldDirName, "\\*.*");

if (sNewPath.Right(1) != "\\")
sNewPath += "\\";
if (sOldPath.Right(1) != "\\")
sOldPath += "\\";

dir = FindFirstFile(sOldDirName, &fd );
if(dir != NULL && dir != INVALID_HANDLE_VALUE)
{
while (1)
{
if(dir != NULL)
{
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (strcmp(fd.cFileName, ".") == 0 || strcmp(fd.cFileName, "..") == 0)
{
}
else
{
//recursively call our function to get sub dirs
if (MoveDirectory(sOldPath + fd.cFileName, sNewPath + fd.cFileName))
DeleteFolder(sOldPath + fd.cFileName);
}
}
else
{
//Build the full path to the old file
strcpy(sOldFileName, sOldPath);
strcat(sOldFileName, fd.cFileName);

//Build the full path to the new file
strcpy(sNewFileName, sNewPath);
strcat(sNewFileName, fd.cFileName);

//Move to new folder
int iRet = rename(sOldFileName, sNewFileName);

}

//Check the next file - if not found then exit
if(!FindNextFile(dir, &fd))
{
break;
}
}
else
break;
}
}
FindClose(dir);


return TRUE;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top