封装成类FileOP
//cpp file
#include "FileOP.h"
BOOL FileOP::CopyDir(CString srcDirPath,CString destDirPath,BOOL bFailExists) {
CFileFind ff;
TRACE(srcDirPath);
TRACE(destDirPath);
if(srcDirPath.Right(1) != "\\")
srcDirPath += "\\";
if(destDirPath.Right(1) != "\\")
destDirPath += "\\";
//judement if srcDirPath&destDirPath exists
if(!DirExists(srcDirPath.Left(srcDirPath.GetLength()-1))) {
return FALSE;
}
if(!DirExists(destDirPath.Left(destDirPath.GetLength()-1))) {
return FALSE;
}
//get src directory name
CString tname = srcDirPath;
tname.Delete(tname.GetLength()-1,1);
int nameLen = tname.GetLength()-(tname.ReverseFind('\\')+1);
CString name = tname.Right(nameLen);
destDirPath += name + "\\";
CreateDir(destDirPath);
BOOL bRet = FALSE;
BOOL bFound = ff.FindFile(srcDirPath+"*");
while(bFound) {
bFound = ff.FindNextFile();
if(ff.GetFileName() == "." || ff.GetFileName() == "..")
continue;
if(ff.IsDirectory()) {
bRet = CopyDir(ff.GetFilePath(),destDirPath);
}else{
bRet = CopyFile(ff.GetFilePath(),destDirPath+ff.GetFileName(),bFailExists);
}
if(!bRet)
break;
}
ff.Close();
return bRet;
}
BOOL FileOP::DirExists(CString dirPath) {
WIN32_FIND_DATA fd;
BOOL ret = FALSE;
HANDLE hFind = FindFirstFile(dirPath, &fd);
if ((hFind != INVALID_HANDLE_VALUE) && (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
//目录存在
ret = TRUE;
}
FindClose(hFind);
return ret;
}
BOOL FileOP::CreateDir(CString dirPath) {
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle = FALSE;
sa.lpSecurityDescriptor = NULL;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
return ::CreateDirectory(dirPath,&sa);
}
header file
#if !defined __FILLOP_H
#define __FILLOP_H
#include "stdafx.h"
class FileOP {
public:
FileOP(){};
~FileOP(){};
static BOOL CopyDir(CString srcDirPath,CString destDirPath,BOOL bFailExists = FALSE);
static BOOL DirExists(CString dirPath);
static BOOL CreateDir(CString dirPath);
};
#endif