c++指定路径,获取该路径下全部文件夹名称(不包括子文件夹)

如何获取指定路径下全部文件夹名称

  1. 获取文件名称
  2. 正则表达式筛选
  3. 输出为文件txt格式
#include<iostream>
#include<vector>
#include <regex>
#include<io.h>
#include<fstream>
using namespace std;

//根据路径,获取该路径下文件夹的名称
void getSubdirs(string path, vector<string>& files);

int main()
{
    //所需要的格式-----匹配标准
    string format("^[a-z]{2}[0-9]{3}");
    string filePath("E:\s");
    //储存所有的文件夹名称
    vector<string> filenames;
    //储存需要的筛选结果
    vector<string> results;
    //结果输出为文件txt
    ofstream outFile;
    //输出文件的路径
    outFile.open("E:/results.txt");
    //获取文件名
    getSubdirs(filePath, filenames);
    //筛选
    regex r(format);
    for (int i = 0; i < filenames.size(); i++) {
        cout << "目前匹配:" << filenames[i] << endl;
        //写入txt
        outFile << "目前匹配:" << filenames[i] << endl;
        if (regex_match(filenames[i], r)) {
            
            cout << "success" << endl;
            outFile << "success" << endl;
            //储存筛选成功结果
            results.push_back(filenames[i]);

        }
        else {
            cout << "fail" << endl;
            //写入txt
            outFile << "fail" << endl;
        }
    }
    cout << "筛选结果如下:" << endl;
    outFile << "筛选结果如下:" << endl;
    cout << "文件夹总数:" << filenames.size() << ",符合要求的数量:" << results.size() << endl;
    outFile << "文件夹总数:" << filenames.size() << ",符合要求的数量:" << results.size() << endl;
    for (int i = 0; i < results.size(); i++) {
        cout << i + 1 << ":" << results[i] << endl;
        outFile << i + 1 << ":" << results[i] << endl;
    }
    //关闭文件
    outFile.close();
    return 0;
}

//获取该路径下文件夹的名称函数的实现
void getSubdirs(string path, vector<string>& files)
{
    long long hFile = 0;
    struct _finddata_t fileinfo;
    string p;
    if ((hFile = _findfirst(p.assign(path).append("/*").c_str(), &fileinfo)) != -1)
    {
        do
        {
            if ((fileinfo.attrib & _A_SUBDIR))
            {
                if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
                    files.push_back(fileinfo.name);
            }
            else
            {
                ;
            }
        } while (_findnext(hFile, &fileinfo) == 0);

        _findclose(hFile);
    }
}










  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值