在文件夹内搜索所有指定格式的文件内容,并按顺序播放。本程序中以图像为例演示。
主要用到_finddata_t、_findfirst、_findnext、_findclose等结构体(
_finddata_t
)或函数(其他三个)。他们都属于io.h头文件。
首先是头文件库如下:
- #include "stdafx.h"
- #include "iostream"
- #include "string"
- #include <vector>
- #include <io.h>
- #include <opencv2/opencv.hpp>
- using namespace cv;
- using namespace std;
主函数,实现操作:
- int _tmain(int argc, _TCHAR* argv[])
- {
- // 图像文件夹
- string file_path = "D:\\image\\";
- // 图像文件路径
- string search_path = file_path + "*.png";
- vector<string> file_list;
- // 搜索指定路径下的所有.png文件
- if (!get_filelist_from_dir(search_path, file_list))
- {
- cout << "open file error!" << endl;
- }
- for (int i = 0 ; i < file_list.size(); i++)
- {
- string dstimage_path = file_path + file_list[i];
- Mat Image = imread(dstimage_path);
- /*-------------------------------------------------*/
- /*可以在次数插入对图像的其他操作*/
- /*-------------------------------------------------*/
- // 显示
- imshow("【显示图像】", Image);
- char ckey = waitKey(5);
- // 按下Esc键则退出程序
- if(ckey == 27)
- {
- return 0;
- }
- }
- return 0;
- }
对于路境内的指定文件,这里是用的.png的图像,当然你也可以用这个方法来处理诸如.bmp、.jpg等其他图像;也可以是用这种方式来处理.txt等非图像文件,套路是不变的!
其中的bool get_filelist_from_dir(string path, vector<string>& files);函数实现文件寻找功能,如下:
- bool get_filelist_from_dir(string path, vector<string>& files)
- {
- long hFile = 0;
- struct _finddata_t fileinfo;
- files.clear();
- if((hFile = _findfirst(path.c_str(), &fileinfo)) != -1)
- {
- do
- {
- if(!(fileinfo.attrib & _A_SUBDIR))
- files.push_back(fileinfo.name);
- }
- while(_findnext(hFile, &fileinfo) == 0);
- _findclose(hFile);
- return true;
- }
- else
- return false;
- }
这里面也没什么难度,只是以前没有见过开头所说的那几个函数的话,确实就不太了解。
对于函数的内容,MSDN就可以查看,不多赘述了。