c++文件夹的清空

此方法可以清空文件夹中的所有东西, 即使有子文件夹也可以清除,希望能帮到你

调用 :  清除文件夹 "数据" 中的文件

DeleteAllFile("C:\\Users\\Administrator\\Desktop\\数据")

 下面是完整的代码:

void DeleteFiles::DeleteAllFile(string strPath)
{
	strPath += "\\*";
	DeleteAllFiles( strPath);
}

// 删除文件夹下的文件
void DeleteFiles::DeleteAllFiles(string strPath)
{
	_finddata_t dir_info;  // 文件夹信息
    _finddata_t file_info;  // 文件信息
	intptr_t f_handle;

	char tmp_path[_MAX_PATH];

	if((f_handle = _findfirst(strPath.c_str(),&dir_info)) != -1)
	{
		while ((_findnext(f_handle,&file_info)) == 0)
		{
			if (is_special_dir(file_info.name))
				continue;
			if(is_dir(file_info.attrib))   //如果是目录,生成完整的路径
			{
				get_file_path(strPath.c_str(), file_info.name, tmp_path);
				DeleteAllFiles(tmp_path);    //开始递归删除目录中的内容
                tmp_path[strlen(tmp_path) - 2] = '\0';
				if(file_info.attrib == 20)
                    printf("This is system file, can't delete!\n");
				else
				{
					// 删除空目录,必须在递归返回前调用 _findclose, 否则无法删除目录
					if (_rmdir(tmp_path) == -1)
						show_error();//目录非空则会显示出错原因
				}
			}
			else
			{
				strcpy_s(tmp_path,strPath.c_str());
				tmp_path[strlen(tmp_path) - 1] = '\0';
				strcat_s(tmp_path,file_info.name);  // 生成完整文件路径

				if(remove(tmp_path) == -1)
                {
                    show_error(file_info.name);
                }
			}
		}
		_findclose(f_handle);//关闭打开的文件句柄,并释放关联资源,否则无法删除空目录
	}
	else
	{
		show_error();//若路径不存在,显示错误信息
	}
}

//判断是否是".."目录和"."目录
inline bool DeleteFiles::is_special_dir(const char *path)
{
	return strcmp(path, "..") == 0 || strcmp(path, ".") == 0;
}


//判断文件属性是目录还是文件
inline bool DeleteFiles::is_dir(int attrib)
{
    return attrib == 16 || attrib == 18 || attrib == 20;
}


inline void DeleteFiles::get_file_path(const char *path, const char *file_name, char *file_path)
{
    strcpy_s(file_path, sizeof(char) * _MAX_PATH, path);
    file_path[strlen(file_path) - 1] = '\0';
    strcat_s(file_path, sizeof(char) * _MAX_PATH, file_name);
    strcat_s(file_path, sizeof(char) * _MAX_PATH, "\\*");
}


//显示删除失败原因
inline void DeleteFiles::show_error(const char *file_name)
{
    errno_t err;
    _get_errno(&err);
    switch(err)
    {
    case ENOTEMPTY:
        printf("Given path is not a directory, the directory is not empty, or the directory is either the current working directory or the root directory.\n");
        break;
    case ENOENT:
        printf("Path is invalid.\n");
        break;
    case EACCES:
        printf("%s had been opend by some application, can't delete.\n", file_name);
        break;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值