Ubuntu下c++读取指定目录及子目录下所有的图片类型文件路径或名字

前言

Linux版本需要用c++读取指定目录下的图片文件的路径。第一次编写出只包含当前目录下的图片文件,并不满足需求。然后重新编写后子目录的文件图片也可以满足。


提示:以下是本篇文章正文内容,下面案例可供参考

一、Ubuntu下c++读取指定目录及子目录下所有的图片类型文件路径或名字

1.代码

代码如下(示例):

#include <string.h>
#include <dirent.h>
#include<iostream>
#include <string>
#include <vector>

using namespace std;


int readFileList(string basePath,vector<string> &files)
{
    DIR *dir;
    struct dirent *ptr;
 

    if ((dir=opendir(basePath.c_str())) == NULL)
    {
        perror("Open dir error...");
        exit(1);
    }

    while ((ptr=readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)    ///current dir OR parrent dir
            continue;
        else if(ptr->d_type == 8)    ///file
        {
            string a = ptr->d_name;
            int pe = a.find_last_of(".");
            string pic_name = a.substr(pe + 1);
            if (pic_name=="jpg") //若想获取其他类型文件只需修改jpg为对应后缀
            {
                string tmpname = basePath + "/" + ptr->d_name;
                files.push_back(tmpname);
                //name.push_back(ptr->d_name)
            }
        }
        else if(ptr->d_type == 4)    ///dir
        {
            string base = basePath + "/" + ptr->d_name;
            readFileList(base,files);
        }
    }
    closedir(dir);
    return 1;
}

int main()
{
    vector<string> temp;//文件路径
    //vector<string> name;//若要只获取文件名称 修改为 readFileList("/home/yao/codes/imgtest", temp,name);

    readFileList("/home/yao/codes/imgtest", temp);
    for (int i = 0; i<temp.size(); i++) {

        cout << temp[i] << endl;
        //cout << name[i] << endl;
    }
    return 0;
}



2.运行结果

在这里插入图片描述

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值