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("http://*").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 + "http://" + 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 + "http://" + 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;}