C++遍历文件夹及其下所有文件和子文件夹

试过一个好用的,不过只能用于windows系统:

#include <io.h>

using namespace std;

void getFiles(string path, vector<string>& files)
{
    //文件句柄
    intptr_t hFile = 0;
    //文件信息
    struct _finddata_t fileinfo;
    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));
                //cout << files.back() << endl;
            }
        } while (_findnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}

int main()
{
	// 文件目录路径
	string filePath = ORG_IMG_DIR_PATH;
	//存放文件路径的容器
	vector<string> vec_img_path;
	 //获取该路径下的所有文件
    getFiles(filePath, m_vec_img_path);
}

项目用到64位,很多算法32位的不好用。
一个简单的64位递归算法;

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

using namespace std;

vector<string> vec_path;

bool TraverseDirectory(std::string path)
{
	__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);
			}
		}
		else	//判断是文件
		{
			string newPath = path + "\\" + FileInfo.name;
			//自定义操作
			vec_path.push_back(newPath);
		}
	} while (_findnext64(Handle, &FileInfo) == 0);

	_findclose(Handle);
	return true;
}
int main()
{
	string input_path = "E:\\cascade\\Paijiu_long\\indoorCVPR_09\\Images\\";
	//调用递归算法
	TraverseDirectory(input_path);
	
	return 0;
}

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值