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

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 您好,YAML 中的多级数组可以通过让数组中的每个元素再包含一个数组来表示。例如: ``` - element1 - element2 - - subelement1 - subelement2 - subelement3 - element3 ``` 这样就表示了一个多级数组,第三个元素是一个包含了三个子元素的数组。 在代码中,你可以通过遍历数组来访问这个多级数组的每一个元素。例如: ```python import yaml data = yaml.load(""" - element1 - element2 - - subelement1 - subelement2 - subelement3 - element3 """, Loader=yaml.FullLoader) for element in data: if isinstance(element, list): for subelement in element: print(subelement) else: print(element) ``` 这段代码会输出这个多级数组中的所有元素,如果某个元素是一个数组,就会遍历这个数组中的所有子元素。 ### 回答2: c 语言中可以使用 yaml-cpp 库来解析多级数组。该库是一个 C++ 实现的开源库,用于读取和写入 YAML 格式的文件。 使用 yaml-cpp 库来解析多级数组,需要先安装该库并包含相关的头文件。首先,创建一个 YAML 文档对象。然后,使用该对象的方法来读取 YAML 文件中的数据。 在 YAML 文件中,多级数组可以表示为嵌套的列表或映射。例如,以下是一个包含多级数组的 YAML 文件示例: ```yaml - [1, 2, 3] - [4, 5, 6] - [7, 8, 9] ``` 在 C++ 中,你可以使用 yaml-cpp 库来解析上述 YAML 文件: ```cpp #include <yaml-cpp/yaml.h> #include <iostream> int main() { YAML::Node doc = YAML::LoadFile("example.yaml"); // 遍历多级数组 for (const auto& array : doc) { for (const auto& element : array) { std::cout << element.as<int>() << " "; } std::cout << std::endl; } return 0; } ``` 运行上述代码,将会输出如下结果: ``` 1 2 3 4 5 6 7 8 9 ``` 上述代码中,`YAML::LoadFile()` 方法用于从 YAML 文件中加载数据并返回一个 YAML::Node 对象。通过遍历该 Node 对象,可以依次访问多级数组中的元素,并使用 `as<int>()` 方法将元素转换为整数类型并输出。 这样,就可以使用 yaml-cpp 库来解析和处理多级数组的 YAML 数据了。 ### 回答3: c语言中要解析多级数组的yaml文件,可以使用yaml-cpp库来实现。yaml-cpp是一个C++的库,提供了对yaml文件的解析和生成功能。 首先,需要下载并安装yaml-cpp库。安装完成后,可以通过以下代码来解析多级数组的yaml文件: ```c++ #include <iostream> #include <yaml-cpp/yaml.h> int main() { YAML::Node config = YAML::LoadFile("config.yaml"); // 读取多级数组 if (config["array"]) { YAML::Node array = config["array"]; for (int i = 0; i < array.size(); i++) { for (int j = 0; j < array[i].size(); j++) { std::cout << "array[" << i << "][" << j << "]: " << array[i][j].as<int>() << std::endl; } } } return 0; } ``` 在上面的代码中,首先通过`YAML::LoadFile`函数将yaml文件加载为一个YAML::Node对象,然后通过索引访问多级数组中的具体元素。 需要注意的是,yaml文件中的数组可以有不同的数据类型,因此需要根据实际情况使用`as`函数来将节点转换为正确的数据类型。 以上就是使用c语言解析多级数组的yaml文件的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值