C++ 文件夹,文件的搜索

需要#include <io.h>

使用了_findfirst, _findnext, _findclose

注意:在X64的系统下_findfirst()返回的handle是long long型的,如果是long 或int 会在_findnext()的时候报错

#include <io.h>


void find_fold(const char* mainDir, std::vector<string> &files)
{
    files.clear();
    intptr_t hFile; //win10 need long long or intptr_t, long will show error
    _finddata_t fileinfo;

    char findDir[250];
    strcpy_s(findDir, mainDir);
    strcat_s(findDir, "\\*.*");

    if ((hFile = _findfirst(findDir, &fileinfo)) != -1)
    {
        do
        {
            if ((fileinfo.attrib & _A_SUBDIR))//find fold
            {
                if (fileinfo.name[0] == '.') //avoid . ..
                    continue;
                char filename[_MAX_PATH];
                strcpy_s(filename, mainDir);
                strcat_s(filename, "\\");
                strcat_s(filename, fileinfo.name);
                string temfilename = filename;
                files.push_back(temfilename);
                cout << temfilename << endl;
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

void find_file(const char* mainDir, std::vector<string> &files)
{
    files.clear();
    intptr_t hFile; //win10 need long long or intptr_t, long will show error
    _finddata_t fileinfo;

    char findDir[250];
    strcpy_s(findDir, mainDir);
    strcat_s(findDir, "\\*.jpg");

    if ((hFile = _findfirst(findDir, &fileinfo)) != -1)
    {
        do
        {
            if (!(fileinfo.attrib & _A_SUBDIR))//find fold
            {
                if (fileinfo.name[0] == '.') //avoid . ..
                    continue;
                char filename[_MAX_PATH];
                strcpy_s(filename, mainDir);
                strcat_s(filename, "\\");
                strcat_s(filename, fileinfo.name);
                string temfilename = filename;
                files.push_back(temfilename);
                cout << temfilename << endl;
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

void main()
{
    std::vector<string> files;
    find_fold(trainDir, files);  //find folder first

    for (auto d : files)
    {
        std::vector<string> jpgs;
        find_file(d.c_str(), jpgs);  //find file in each folder

    }
}

参考

test for safe only

C/C++ 获取文件夹下的所有文件列表_yhl_leo-CSDN博客

c++ 遍历目录下文件_Rachel Zhang的专栏-CSDN博客_c++ 目录

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值