#include<iostream>
#include<string>
#include<set>
#include<windows.h>
#include<strsafe.h>
#include<direct.h>
//迭代输出目录下所有文件
void recurseFiles(const std::string& path, std::set<std::string>& files)
{
WIN32_FIND_DATA fileInfo;
HANDLE h_find = NULL;
std::string assetPath;
h_find = FindFirstFileA(assetPath.assign(path).append("\\*").c_str(), &fileInfo);
if(h_find != INVALID_HANDLE_VALUE)
{
_chdir(path.c_str());// 此处关闭即可正常删除整个目录,否则会留下目录中最后一个子目录
do
{
if(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(strcmp(fileInfo.cFileName, ".") && strcmp(fileInfo.cFileName, ".."))
{
recurseFiles(assetPath.assign(path).append("\\").append(fileInfo.cFileName), files);
}
}
else
{
files.insert(assetPath.assign(path).append("\\").append(fileInfo.cFileName));
}
} while(FindNextFileA(h_find, &fileInfo]));
}
FindClose(h_find);
}
// 输出错误信息
void reportError()
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD lastError = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
lastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL
);
lpDisplayBuf = (LPVOID) LocalAlloc(LMEM_ZEROINIT, lstrlen((LPCTSTR)lpMsgBuf) + MAX_PATH) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf), TEXT("%s failed with error %d : %s"), "RemoveAll", lastError, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
// 删除整个path目录
void removeAllFiles(const std::string& path)
{
WIN32_FIND_DATA fileInfo;
HANDLE h_find = NULL;
std::string assetPath;
h_find = FindFirstFileA(assetPath.assign(path).append("\\*").c_str(), &fileInfo);
if(h_find != INVALID_HANDLE_VALUE)
{
do
{
if(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(strcmp(fileInfo.cFileName, ".") && strcmp(fileInfo.cFileName, ".."))
{
recurseFiles(assetPath.assign(path).append("\\").append(fileInfo.cFileName), files);
}
}
else
{
DWORD dwAttribute = ::GetFileAttributesA(assetPath.assign(path).append("\\").append(fileInfo.cFileName).c_str());
if(dwAttribute & FILE_ATTRIBUTE_READONLY)
{
dwAttribute &= ~FILE_ATTRIBUTE_READONLY;
SetFileAttributeA(assetPath.c_str(), dwAttribute);
}
if(!DeleteFileA(assetPath.c_str()))
{
reportError();
}
}
} while(FindNextFileA(h_find, &fileInfo));
}
FindClose(h_find);
if(!RemoveDirectoryA(path.c_str()))
{
reportError();
}
}
void main()
{
std::string sourcePath("D:\\Sheldon\\My Project");
std::set<std::string> allFiles;
recurseFiles(sourcePath, allFiles);
for(auto it = allFiles.begin(); it != allFiles.end(); it++)
{
std::cout << *it << std::endl;
}
removeAllFiles(sourcePath);
getchar();
}
chdir导致无法删除最后一个子文件夹
最新推荐文章于 2019-08-25 19:10:00 发布