c++ 遍歷多級目錄

參考:https://blog.csdn.net/sazass/article/details/100163264

TraverseDirectory可以遍歷多級目錄

getFiles不能遍歷多級目錄

#include "stdafx.h"

#include <stdio.h>
#include <tchar.h>

#include <vector>
#include <algorithm>
#include <caffe/caffe.hpp>
#include <fstream>

using namespace std;
using namespace caffe;
typedef unsigned char BYTE;


#include <io.h>
#include <stdio.h>

int endsWith(string s, string sub) {
	return s.rfind(sub) == (s.length() - sub.length()) ? 1 : 0;
}
void getFiles(string path, vector<string>& files, string postfix)
{
	intptr_t hFile = 0;
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(p.assign(path).append("\\*"), files, postfix);
			}
			else
			{
				string filename = fileinfo.name;

				if (postfix.size() == 0 || (postfix.size() > 0 && endsWith(filename, postfix) && (postfix.c_str(), strchr(fileinfo.name, '.'))))
					files.push_back(p.assign(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

bool TraverseDirectory(std::string path, vector<string>& vec_path, string postfix)
{
	__int64  Handle;
	struct __finddata64_t  FileInfo;
	string strFind = path + "\\*";

	if ((Handle = _findfirst64(strFind.c_str(), &FileInfo)) == -1L)
	{
		printf("沒有找到匹配的項目\n");
		return false;
	}
	do
	{
		//判斷是否有子目錄
		if (FileInfo.attrib & _A_SUBDIR)
		{
			//判斷是子文件夾
			//下面的判斷條件很重要,過濾 . 和 ..
			if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0))
			{
				string newPath = path + "\\" + FileInfo.name;
				TraverseDirectory(newPath, vec_path, postfix);
			}
		}
		else	//判斷是文件
		{
			string newPath = path + "\\" + FileInfo.name;
			//自定義操作
			if (postfix.size() == 0 || (postfix.size() > 0 && endsWith(newPath, postfix) && (postfix.c_str(), strchr(newPath.c_str(), '.'))))
			vec_path.push_back(newPath);
		}
	} while (_findnext64(Handle, &FileInfo) == 0);

	_findclose(Handle);
	return true;
}

#include <string.h>
#include <Windows.h>    
char sBuf[1024];
char *ptr;
int main(int argc, char* argv[]) {
	if (caffe::GPUAvailable()) {
		caffe::SetMode(caffe::GPU, 0);
	}

	if (GetModuleFileNameA(NULL, sBuf, sizeof(sBuf)))
	{
		ptr = strrchr(sBuf, '\\');
		if (ptr)
			*ptr = '\0';
		SetCurrentDirectoryA(sBuf);
	}

	int result= init("model");
	int detect_model= 1;

	std::vector<std::string> files_1;
	getFiles(R"(D:\BaiduNetdiskDownload\CASIA\CASIA-WebFace)", files_1, ".jpg");

	vector<string> vec_path;

	TraverseDirectory(R"(D:\BaiduNetdiskDownload\CASIA\CASIA-WebFace)", files_1, ".jpg");

 

 

只能遍歷一級目錄


//created:2020.04.06 by Andison
 
#include<iostream>
#include<vector>
#include<algorithm>
#include <opencv2/opencv.hpp>
using namespace std;
//讀取路徑下的特定格式文件的路徑,返回按文件名升序排列的文件路徑vector
int getFilePaths(vector<string> &filepaths, cv::String filePath);
 
int main()
{
	vector<string> filePaths;
	cv::String folderPath = "C:\\Users\\sun\\Desktop\\paths\\*.txt";
	double t1 = cv::getTickCount();
	getFilePaths(filePaths, folderPath);
	double t2 = cv::getTickCount();
	cout << "Time elapsed: " << 1000 * (double)(t2 - t1) / cv::getTickFrequency() <<" ms."<< endl;
 
	getchar();
	return 0;
}
// 名稱按升序排列,來源博客: https://blog.csdn.net/sss_369/article/details/87740843
int  getFilePaths(vector<string> &filepaths, cv::String filePath)
{
	filepaths.clear();
	cout << "Read files from: " << filePath << endl;
	vector<cv::String> fn;
	cv::glob(filePath, fn, false);
 
	if (fn.size() == 0)
	{
		cout << "file " << filePath << " not  exits" << endl;
		return -1;
	}
	//prepare pair for sort 
	vector<pair<int, string>> v1;
	pair<int, string> p1;
	vector<cv::String >::iterator it_;
	for (it_ = fn.begin(); it_ != fn.end();	++it_)
	{	
		//1.獲取不帶路徑的文件名,1.txt
		string::size_type iPos = (*it_).find_last_of('\\') + 1;
		string filename = (*it_).substr(iPos, (*it_).length() - iPos);
		//2.獲取不帶後綴的文件名,1
		string name = filename.substr(0, filename.rfind("."));
		//3.構建鍵和值的pair
		try {
			//防止文件夾中出現非整數的文件名導致的錯誤
			p1 = make_pair(stoi(name), (*it_).c_str());
 
		}catch(exception e)
		{
			cout << "Crushed -> " << e.what() << endl;
			//continue; 直接continue一樣 
			it_ = fn.erase(it_);
			//https://www.cnblogs.com/shiliuxinya/p/12219149.html
			it_--; //erase函數的返回的是指向被刪除元素的下一個元素的迭代器,所以執行erase()後要把迭代器減1,指向前面一個
		}
		v1.emplace_back(p1);
	}
	//cout << "v1.sie(): " << v1.size()<<endl;
	sort(v1.begin(), v1.end(), [](auto a, auto b) {return a.first < b.first; });
	vector<pair<int, string> >::iterator it;
	for (it = v1.begin(); it != v1.end(); ++it)
	{
		//cout << it->first << endl;
		//cout << it->second << endl;
 
		filepaths.emplace_back(it->second);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章