一、使用 _rmdir和remove
#include <iostream>
#include <io.h>
#include <fstream>
#include <sys/stat.h>
//递归删除目录下所有文件
void removeDir(string dirPath)
{
struct _finddata_t fb; // 查找相同属性文件的存储结构体
string path;
long long handle; // 注意此处需要long*2
int noFile; // 对系统隐藏文件的处理标记
noFile = 0;
handle = 0;
struct stat s;
if (stat(dirPath.c_str(), &s) == 0) {
if (s.st_mode & S_IFDIR) {
std::cout << "it's a directory" << std::endl;
}
else if (s.st_mode & S_IFREG) {
std::cout << "it's a file" << std::endl;
}
else {
std::cout << "not file not directory" << std::endl;
}
}
else {
std::cout << "error, doesn't exist" << std::endl;
return;
}
path = dirPath + "/*";
handle = _findfirst(path.c_str(), &fb);
// 找到第一个匹配的文件
if (handle != 0)
{
// 当可以继续找到匹配的文件,继续执行
while (0 == _findnext(handle, &fb))
{
// windows下,常有个系统文件,名为“..”,对它不做处理
noFile = strcmp(fb.name, "..");
if (0 != noFile)
{
path = dirPath + "/" + fb.name;
// 属性值为16,则说明是文件夹,迭代
if (fb.attrib == 16)
{
removeDir(path);
}
// 非文件夹的文件,直接删除。对文件属性值的情况没做详细调查,可能还有其他情况。
else
{
remove(path.c_str());
}
}
}
//删除空目录
_rmdir(dirPath.c_str());
// 关闭文件夹,只有关闭了才能删除。找这个函数找了很久,标准c中用的是closedir
// 经验介绍:一般产生Handle的函数执行后,都要进行关闭的动作。
_findclose(handle);
}
}
int main()
{
removeDir(L"E:\\test");
return 0;
}
二、使用 RemoveDirectory和DeleteFile
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
void RemoveAllFiles(wstring wstrDir)
{
if (wstrDir.empty())
{
return;
}
HANDLE hFind;
WIN32_FIND_DATA findData;
wstring wstrTempDir = wstrDir + (L"\\*");;
hFind = FindFirstFile(wstrTempDir.c_str(), &findData);
if (hFind == INVALID_HANDLE_VALUE)
{
return;
}
do
{
// 忽略"."和".."两个结果
if (wcscmp(findData.cFileName, L".") == 0 || wcscmp(findData.cFileName, L"..") == 0)
{
continue;
}
wstring wstrFileName;
wstrFileName.assign(wstrDir);
wstrFileName.append(L"\\");
wstrFileName.append(findData.cFileName);
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)// 是否是目录
{
RemoveAllFiles(wstrFileName.c_str());
}
else
{
DeleteFile(wstrFileName.c_str());
}
} while (FindNextFile(hFind, &findData));
FindClose(hFind);
RemoveDirectory(wstrDir.c_str());
}
int main()
{
RemoveAllFiles(L"E:\\test");
return 0;
}