windows下用c++和python遍历目录下的文件夹并删除所有文件名为xx的文件

时间:2021-05-23 12:24:03

python版本:

import os
import shutil

def deleteF(path, fileName):
for files in os.listdir(path):
tmpPath = os.path.join(path, files)
filePath = os.path.join(path, fileName)
if os.path.isdir(tmpPath):# 如果是文件夹,递归
deleteF(tmpPath, fileName)
elif os.path.isfile(filePath):#如果是文件,删除
os.remove(filePath)
print "deleted file in " + files

deleteF('E:\\py\\test', 'back1.bmp')

c++版本:


#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;
}