简介
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;
}