首页 > 编程 > C++ > 正文

windows下用c++遍历目录下的文件夹并删除文件

2019-11-06 06:39:31
字体:
来源:转载
供稿:网友
#include <stdio.h>#include <iostream>#include <io.h>#include <string>using namespace std;void dir(string path){ long hFile = 0; struct _finddata_t fileInfo; string pathName, exdName; // //* 代表要遍历所有的类型 if ((hFile = _findfirst(pathName.assign(path).append("//*").c_str(), &fileInfo)) == -1) { cout << "error no file!" << endl; return; } do { //判断文件的属性是文件夹还是文件 cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl; //如果是文件夹就进入文件夹,迭代 if (fileInfo.attrib&_A_SUBDIR) { {//遍历文件系统时忽略"."和".."文件 if (strcmp(fileInfo.name, ".") != 0 && strcmp(fileInfo.name, "..") != 0) { string tmp; tmp = path + "//" + fileInfo.name; dir(tmp); } } } //是文件的话就查看文件名,不是“back1.bmp”就删除 else { //delete file if (strcmp(fileInfo.name, ".") != 0 && strcmp(fileInfo.name, "..") != 0) { if (strcmp(fileInfo.name, "back1.bmp")) { string delpath = path + "//" + fileInfo.name; if (remove(delpath.c_str()) != 0)//删除失败就报错 perror("Error deleting file"); else { cout << fileInfo.name << "deleted" << endl; } } } } } while (_findnext(hFile, &fileInfo) == 0); _findclose(hFile); return;}int main(){ //要遍历的目录 string path = "E://inpainting//pics"; dir(path); system("pause"); return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选