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

13 篇文章 0 订阅
10 篇文章 0 订阅

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值