Advertisement

C++ 提取某一文件夹下的所有文件的名称

阅读量:

由于OpenCV添加lib项太多,使用C++处理产生同一文件夹下的所有文件名称,节省大量时间,

需要注意的是在win64的系统下long hFile的文件名称会报错,这时采用ling long型来定义文件路径索引,

还有就是用到字符串裁剪,在通过gefile读入的字符串是带有文件目录信息的,采用string.substr来对文件名称进行裁剪,达到希望的输出,具体代码如下:

复制代码
 #include "stdafx.h"

    
 #include <iostream>  
    
 #include <io.h>  
    
 #include <string>  
    
 #include <vector>  
    
 using namespace std;
    
  
    
 void getFiles(const std::string & path, std::vector<std::string> & files)
    
 {
    
 	//文件句柄  
    
 	long long hFile = 0;
    
 	//文件信息,_finddata_t需要io.h头文件  
    
 	struct _finddata_t fileinfo;
    
 	std::string p;
    
 	if ((hFile = _findfirst(p.assign(path).append("\ *").c_str(), &fileinfo)) != -1)
    
 	{
    
 		do
    
 		{
    
 			//如果是目录,迭代之  
    
 			//如果不是,加入列表  
    
 			if ((fileinfo.attrib & _A_SUBDIR))
    
 			{
    
 				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
    
 					getFiles(p.assign(path).append("\ ").append(fileinfo.name), files);
    
 			}
    
 			else
    
 			{
    
 				files.push_back(p.assign(path).append("\ ").append(fileinfo.name));
    
 			}
    
 		} while (_findnext(hFile, &fileinfo) == 0);
    
 		_findclose(hFile);
    
 	}
    
 }
    
  
    
 int main()
    
 {
    
 	vector<std::string> filenames;//用来存储文件名
    
 	string path = "D:\ opencvbuild\ install\ x64\ vc15\ lib";
    
 	int length = path.length();
    
 	getFiles(path, filenames);
    
 	for (auto file : filenames)
    
 	{
    
 		cout << file.substr(length + 1) << std::endl;
    
 	}
    
 	system("pause");
    
 	return 0;
    
 }
    
    
    
    

效果图如下:

全部评论 (0)

还没有任何评论哟~