C++ 递归删除目录下所有文件(包括空目录)

目录

一、使用 _rmdir和remove

二、使用 RemoveDirectory和DeleteFile


一、使用 _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;
}


 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值