windows和Linux c++遍历文件目录

1. windows文件目录遍历

cpp 复制代码
#include <string>

#include <Windows.h>
#include <io.h>
#include <vector>
using namespace std;

void getFiles(const std::string& dir, std::vector<string>& files, const std::string filter_type="*.*")
{
	//文件句柄
	intptr_t   hFile = 0;
	//文件信息
	struct _finddata_t fileinfo;
	std::string path = dir + "\\" + filter_type;
	//string p = "F:\\TY_code\\sqliteR8\\TySrvDevelop\\bin\\TY-CM-2116A2-V1\\snap\\*.jpg";
	if ((hFile = _findfirst(path.c_str(), &fileinfo)) != -1)
	{
		do
		{
			//如果是目录,迭代之
			//如果不是,加入列表
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFiles(fileinfo.name, files);
			}
			else
			{
				string dir = path.substr(0, path.find_last_of("\\")+1);
				files.push_back(dir + fileinfo.name);
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

2. Linux文件目录遍历

cpp 复制代码
#include <dirent.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <string>
 
namespace {
 
void Usage(const char* exe)
{
	fprintf(stderr, "input params error, run this exe as following command line:\n");
	fprintf(stderr, "\t%s arg1 arg2 arg3\n", exe);
	fprintf(stderr, "\targ1: specify the directory to traverse\n");
    fprintf(stderr, "\targ2: type:\n"
        "\t\t0: tarverse all files and all directories in directory;\n"
        "\t\t1: only tarverse all files, don't include directories in directory;\n"
        "\t\t2: only tarverse all directories, don't include files in directory.\n");
    fprintf(stderr, "\targ3: optional, filter, default is *, which is don't filter. \n");
	fprintf(stderr, "for example(support relative path), only traverse jpg image:\n");
	fprintf(stderr, "\t%s ./images 0 .jpg\n", exe);
    fprintf(stderr, "##### test fail #####\n");
}
 
// 遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹
std::vector<std::string> GetListFiles(const std::string& path, const std::string& exten = "*")
{
    std::vector<std::string> list;
    list.clear();
 
    DIR* dp = nullptr;
    struct dirent* dirp = nullptr;
    if ((dp = opendir(path.c_str())) == nullptr) {
        return list;
    }
 
    while ((dirp = readdir(dp)) != nullptr) {
        if (dirp->d_type == DT_REG) {
            if (exten.compare("*") == 0)
                list.emplace_back(static_cast<std::string>(dirp->d_name));
            else
                if (std::string(dirp->d_name).find(exten) != std::string::npos)
                    list.emplace_back(static_cast<std::string>(dirp->d_name));
        }
    }
 
    closedir(dp);
 
    return list;
}
 
// 遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件
std::vector<std::string> GetListFolders(const std::string& path, const std::string& exten = "*")
{
    std::vector<std::string> list;
    list.clear();
 
    DIR* dp = nullptr;
    struct dirent* dirp = nullptr;
    if ((dp = opendir(path.c_str())) == nullptr) {
        return list;
    }
 
    while ((dirp = readdir(dp)) != nullptr) {
        if (dirp->d_type == DT_DIR && strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0) {
            if (exten.compare("*") == 0)
                list.emplace_back(static_cast<std::string>(dirp->d_name));
            else
                if (std::string(dirp->d_name).find(exten) != std::string::npos)
                    list.emplace_back(static_cast<std::string>(dirp->d_name));
        }
    }
 
    closedir(dp);
 
    return list;
}
 
// 遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹
std::vector<std::string> GetListFilesR(const std::string& path, const std::string& exten = "*")
{
    std::vector<std::string> list = GetListFiles(path, exten);
 
    std::vector<std::string> dirs = GetListFolders(path, exten);
 
    for (auto it = dirs.cbegin(); it != dirs.cend(); ++it) {
        std::vector<std::string> cl = GetListFiles(*it, exten);
        for (auto file : cl) {
            list.emplace_back(*it + "/" + file);
        }
    }
 
    return list;
}
 
} // namespace
 
int main(int argc, char* argv[])
{
    if (argc < 3 || argc > 4) {
        Usage(argv[0]);
        return -1;
    }
 
    int type = atoi(argv[2]);
    std::string exten = "*";
    if (argc == 4) exten = std::string(argv[3]);
 
    std::vector<std::string> vec;
    if (type == 0) vec = GetListFilesR(std::string(argv[1]), exten);
    else if (type == 1) vec = GetListFiles(std::string(argv[1]), exten);
    else if (type == 2) vec = GetListFolders(std::string(argv[1]), exten);
    else { Usage(argv[0]); return -1;}
 
    fprintf(stdout, "traverse result: files count: %d\n", vec.size());
    for (auto& file : vec) {
        fprintf(stderr, "\t%s\n", file.c_str());
    }
 
    fprintf(stdout, "===== test success =====\n");
}
相关推荐
如意猴11 分钟前
【C++】007 C/C++ 内存管理机制、malloc与new的区别及模板初阶
java·c++·算法
树下水月11 分钟前
Typora破解
linux·服务器·前端
朝朝辞暮i14 分钟前
C++ 第 32 课:main()、rclcpp::init()、spin()、shutdown()
开发语言·c++·算法
汉克老师19 分钟前
GESP2026年9月认证C++一级( 第三部分编程题(1、新龟兔赛跑))精讲
c++·gesp·小学生·学c++编程
沫璃染墨44 分钟前
《从零入门Linux系统篇(五十七):线程篇·十——生产者消费者模型进阶:从环形缓冲区到POSIX信号量》
linux·运维·服务器·开发语言·c++·系统架构·信号处理
YCOSA20251 小时前
雨晨 Windows 11 IoT 企业版 Edge 轻装 VCDX 29680.1000
windows·物联网
wuminyu1 小时前
LockStack在虚拟线程Mount和Unmount拷贝过程剖析
java·linux·c语言·jvm·c++
深念Y1 小时前
rime-雾凇拼音-配置记录
linux·junit·软件·拼音·kde
知识分享小能手1 小时前
C++ 学习教程,从入门到精通,string类和标准模板库 — 完整知识点详解(16)
开发语言·c++·学习
无忧.芙桃2 小时前
位图妙用:512MB 实现 40 亿整数的存在性查询
c语言·c++·面试·哈希算法