您的位置:首页 > 编程语言 > C语言/C++

C/C++实现文件的备份

2013-05-11 14:12 393 查看
/*以下代码实现从源目录按照目录层级将文件备份到目的地目录*/
#include "iostream"
#include "windows.h"
using namespace std;

void CopyFolder(char path[], char Destpath[],int level = 0)
{
char find_path[256];
char Dest_path[256];
char Dest_pathCopy[256];
char srcPath[256];
sprintf(find_path, "%s*", path);
sprintf(Dest_path, "%s", Destpath);

WIN32_FIND_DATA FindFileData;
HANDLE hFind;
BOOL bContinue = TRUE;

hFind = FindFirstFile(find_path, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
return;
}

while (bContinue)
{
if (stricmp(FindFileData.cFileName, "..") && stricmp(FindFileData.cFileName, "."))
{
for (int i = 0; i < level; ++i)
cout<<"    ";
cout<<"1"<<FindFileData.cFileName<<endl;

// 如果是目录的话:.创建新目录;.递归查找目录下文件
// 如果是文件的话:复制文件到目的地目录下
if (FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
sprintf(find_path, "%s%s\\", path, FindFileData.cFileName);
sprintf(Dest_path, "%s%s\\", Destpath, FindFileData.cFileName);
::CreateDirectory(Dest_path, NULL);
CopyFolder(find_path, Dest_path, level + 1);
}
else
{
strcpy(Dest_pathCopy, Destpath);
char *pos = strrchr(Dest_pathCopy, '\\');
if ( NULL != pos )
{
++pos;
*pos = '\0';
}
strcat(Dest_pathCopy, FindFileData.cFileName);

strcpy(srcPath, path);
pos = strchr(srcPath, '*');
// 		++pos;
if ( NULL != pos )
{
*pos = '\0';
}
strcat(srcPath, FindFileData.cFileName);
BOOL ret = ::CopyFile(srcPath, Dest_pathCopy, FALSE);
}
}
bContinue = FindNextFile(hFind, &FindFileData);

}
}
int main()
{
char szPath[] = "E:\\Film\\";
char destPath[] = "F:\\NEW_Film\\";

CopyFolder(szPath, destPath);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: