c++读取指定目录下所有的图片类型文件路径或名称(包含子目录)

导读:本篇文章讲解 c++读取指定目录下所有的图片类型文件路径或名称(包含子目录),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前言

windows版本需要用c++读取指定目录下的图片文件的路径。第一次编写出只包含当前目录下的图片文件,并不满足需求。然后重新编写后子目录的文件图片也可以满足。


提示:以下是本篇文章正文内容,下面案例可供参考

一、c++读取指定目录下所有的图片类型文件路径或名称(不包含子目录)

1.代码

代码如下(示例):

#include <io.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;

void getAllFiles(string path, vector<string>& files,string fileType) {

	//文件句柄
	intptr_t hFile = 0;
	_finddata_t  fileInfo;
	string p;

	if ((hFile = _findfirst(p.assign(path).append("\\*" + fileType).c_str(), &fileInfo)) != -1) {
		do {
			files.push_back(p.assign(path).append("\\").append(fileInfo.name));
		} while (_findnext(hFile, &fileInfo) == 0);

		_findclose(hFile);//关闭句柄

	}

}

int main() {
	vector<string> temp;
	getAllFiles("H:\\imgtest",temp, ".jpg");

	for (int i = 0; i < temp.size(); i++) {

		cout << temp[i] << endl;
	}
}

2.运行结果

在这里插入图片描述

二、c++读取指定目录下所有的图片类型文件类型或名称(包含子目录)

1.代码

代码如下(示例):

#include<io.h>
#include<iostream>
#include <string>
#include <vector>

using namespace std;

void getFiles(std::string path, std::vector<std::string>& files, std::vector<std::string>& names)
{
	//文件句柄
	intptr_t  hFile = 0;
	//文件信息 
	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, names);
				}
			}
			else
			{
				string a = fileinfo.name;
				int pe = a.find_last_of(".");
				string pic_name = a.substr(pe + 1);
				if (pic_name=="jpg")  // 其他类型文件只需将此处jpg修改即可
				{
					files.push_back(p.assign(path).append("\\").append(fileinfo.name));
					names.push_back(fileinfo.name);
				}
					
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}


int main()
{
	vector<string> temp;
	vector<string> name;
	getFiles("H:\\imgtest", temp,name);

	for (int i = 0; i < temp.size(); i++) {

		cout << temp[i] << endl; //图片具体路径
		//cout << name[i] << endl; //图片名称
	}
	return 0;
}

2.运行结果

在这里插入图片描述

总结

第一次编写,若有不足还将改进。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99642.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!