一、拷贝目录
bool CopyMyDirFlie(const std::string strMyDir, const std::string strDestDir)
{
std::string strDir = strMyDir;
std::string strNewDestDir = strDestDir;
CreateDirectory(strDestDir.c_str(), NULL);
if (strDir.at(strDir.length() - 1) != '\\')
{
strDir.append("\\");
}
if (strNewDestDir.at(strNewDestDir.length() - 1) != '\\')
{
strNewDestDir.append("\\");
}
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile((strDir + "*.*").c_str(), &wfd);
if (hFind == INVALID_HANDLE_VALUE)
{
return false;
}
do
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (_stricmp(wfd.cFileName, ".") != 0 && _stricmp(wfd.cFileName, "..") != 0)
{
CopyMyDirFlie(strDir + wfd.cFileName, strNewDestDir + wfd.cFileName);
}
else
{
CreateDirectory((strNewDestDir + wfd.cFileName).c_str(), NULL);
}
}
else
{
CopyFile((strDir + wfd.cFileName).c_str(), (strNewDestDir + wfd.cFileName).c_str(), FALSE);
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind);
return true;
}
二、删除目录
bool RemoveMyDir(std::string strDir)
{
std::string strOrignDir = strDir;
if (strDir.at(strDir.length() - 1) != '\\')
{
strDir.append("\\");
}
//删除文件夹下所有文件
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile((strDir + "*.*").c_str(), &wfd);
if (hFind == INVALID_HANDLE_VALUE)
{
return false;
}
do
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (_stricmp(wfd.cFileName, ".") != 0 && _stricmp(wfd.cFileName, "..") != 0)
{
RemoveMyDir(strDir + wfd.cFileName);
}
}
else
{
DeleteFile((strDir + wfd.cFileName).c_str());
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind);
//删除该文件夹
if (!RemoveDirectory(strDir.c_str()))
{
DWORD dCode = GetLastError();
if (dCode == ERROR_DIR_NOT_EMPTY)
{
RemoveMyDir(strDir.c_str());
}
return false;
}
return true;
}
三、创建隐藏文件夹
void CreateHideDirectory(std::string strDir)
{
if (!PathIsDirectory(strDir.c_str()))
{
CreateDirectory(strDir.c_str(), NULL);
SetFileAttributes(strDir.c_str(), FILE_ATTRIBUTE_HIDDEN); //设置为隐藏文件夹
}
}
四、判断目录是否存在五
bool CheckFolderExist(const string &strPath)
{
WIN32_FIND_DATA wfd;
bool rValue = false;
HANDLE hFind = FindFirstFile(strPath.c_str(), &wfd);
if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
rValue = true;
}
FindClose(hFind);
return rValue;
}
五、获取目录下所有文件
int MyGetAllFiles(std::string strDir, std::vector<std::string>& filesVec)
{
WIN32_FIND_DATA findData;
std::string strFindFile = strDir + "\\*";
HANDLE hFind = FindFirstFile(strFindFile.c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE)
{
return -1;
}
do
{
if (std::string(findData.cFileName).compare(".") == 0 ||
std::string(findData.cFileName).compare("..") == 0)continue;
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
//如果是目录
std::string strDir1 = strDir + "\\";
strDir1.append(std::string(findData.cFileName).c_str());
MyGetAllFiles(strDir1, filesVec);
}
else
{
filesVec.push_back(strDir + "\\" + std::string(findData.cFileName));
}
} while (FindNextFile(hFind, &findData));
return 0;
}