C++:遍历指定路径下的文件/图片

#include <iostream>
#include <vector>
#include <io.h>
using namespace std;

bool get_filelist_from_dir(std::string path, std::vector<std::string>& files)
{
    long long  hFile = 0;
    //_findnext()第一个参数”路径句柄”,返回的类型为intptr_t(long long),
    //如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t
    struct _finddata_t fileinfo;
    files.clear();
    if ((hFile = _findfirst(path.c_str(), &fileinfo)) != -1)
    {
        do
        {
            cout << fileinfo.name << endl;
            if (!(fileinfo.attrib & _A_SUBDIR))
            {
                files.push_back(fileinfo.name);
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
        return true;
    }
    else
    {
        return false;
    }

    //另一种写法
    //struct _finddata_t fileinfo;
    //long long handle;
    _findnext()第一个参数”路径句柄”,返回的类型为intptr_t(long long),
    如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t
    //handle = _findfirst(path.c_str(), &fileinfo);  //返回文件句柄<br>
    //if (handle == -1)
    //{
    //	cout << "fail..." << endl;
    //	return false;
    //}
    //else
    //{
    //	cout << fileinfo.name << endl;
    //	files.push_back(fileinfo.name);
    //}
    //cout << "#### 1 ####" << endl;
    //while (!_findnext(handle, &fileinfo))
    //{
    //	cout << "#### 2 ####" << endl;
    //	cout << fileinfo.name << endl;
    //}
    //_findclose(handle);
    //return true;
}

vector<string> getImageList(std::string file_path, std::string suffix)
{
    //string file_path = "D:\\image\\";
    //string suffix = "*.png";
    string search_path = file_path + suffix;
    vector<string> file_list;//保存遍历到的文件name
    if (!get_filelist_from_dir(search_path, file_list))
        cout << "open file error!" << endl;
    vector<string> image_path_list;//保存文件绝对路径
    for (int i = 0; i < file_list.size(); i++)
    {
        image_path_list.push_back(file_path + file_list[i]);
        //Mat image = imread(image_path);
        //这里可以对图像进行处理
    }
    return image_path_list;
}

int main()
{
    vector<string> output;
    string filepath = "D:\\image\\";
    string suffix = "*.*";//后缀名
    output = getImageList(filepath, suffix);
    return 0;
}

涉及到了一个结构体,需要用的是name属性,当然假如需要文件大小的话也可以把size提取出来

#define _finddata_t     _finddata64i32_t

struct _finddata64i32_t
{
    unsigned    attrib;
    __time64_t  time_create;    // -1 for FAT file systems
    __time64_t  time_access;    // -1 for FAT file systems
    __time64_t  time_write;
    _fsize_t    size;
    char        name[260];
};

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值