关于dirent API中基本函数的使用--载入数据篇

简介
dirent库其实是C语言的标准库,但是正如C++继承了C语言的许多标准库,所以在按照之前的博客配置好dirent后便可以在C++语言中使用。本文仅仅介绍dirent API中载入目录内容的三个函数,分别是:

  • opendir():用于载入目录,返回一个DIR * 类型的对象,用于指向目录。参数类型是const char*。
  • readdir():用于读取目录中的文件,返回的是一个dirent 类型的结构指针。参数类型是DIR *。
  • closedir():用于关闭目录。参数类型是DIR *。

demo程序
下面是使用如上函数从一个文件夹中读取图片的demo程序。

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/nonfree/features2d.hpp>

#include <iostream>
#include <vector>
#include <string>
#include <ctime>
#include <cstdlib>
#include <cctype>
#include <dirent.h> //载入dirent头文件

using namespace std;

int main(void)
{
    //构建向量存储文件夹中的图片
    vector<cv::Mat> img;

        //保存文件夹路径
    string dir_name;
        //提醒用户输入文件夹路径
        /*
          注意:有两种输入格式
        E:\\file\\file\\ 或者 E:/file/file/
                必须是如上两种格式否则imread无法读取图像。
        */
    cout<<"Please input the path of the directory: (q to quit) \n";
    getline(cin, dir_name);
    if( dir_name == "q")
        return -1;

    //定义一个目录指针
    DIR *pdir = NULL; 
    //定义一个结构体指针
    struct dirent *pent = NULL; 

    //打开目录文件
    pdir = opendir(dir_name.c_str()); 

    if( pdir == NULL)
    {
        cout<<"Fail to open the directory."<<endl;
        return -1;
    }
    unsigned int count = 0u;

    //从文件夹中读取文件,自动遍历
    while( pent = readdir(pdir) ) 
    {
        if( pent == NULL ) //检查是否返回结构体
        {
            cout<<"Nothing remained. \n";
            return -1;
        }

        if( count >= 2u )
        {
            cv::Mat img_input = cv::imread( dir_name + pent->d_name ); //载入图片
            if( img_input.empty() ) //检查图片是否载入
            {
                cout<<"Fail to load the "<<count<<" image.\n";
                continue;
            }
            img.push_back(img_input); //将图片存储在img向量中
            cout<<"Loaded "<<img.size()<<" image.\n";
        }

        count++;
    }
    system("pause");
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值