之前在 https://blog.csdn.net/fengbingchun/article/details/51474728 给出了在Windows遍历指定文件夹的C++实现,这里给出在Linux下遍历目录的实现,Windows和Linux下的实现都是参考了OpenCV 2.x中的实现,OpenCV中的用法可参考https://blog.csdn.net/fengbingchun/article/details/42435901 ,OpenCV 3.x中将这一部分移除掉了。

目前不论是windows、linux还是opencv本身的实现,在目录中嵌套的目录只能遍历一层。

测试代码如下:

#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));elseif (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));elseif (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;
}} // namespaceint 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");
}

CMakeLists.txt文件内容如下:

PROJECT(samples_cplusplus)
CMAKE_MINIMUM_REQUIRED(VERSION 3.0)# 支持C++11
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -O2 -std=c11")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}  -g -Wall -O2 -std=c++11")INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR})FILE(GLOB samples ${PROJECT_SOURCE_DIR}/*.cpp)FOREACH (sample ${samples})STRING(REGEX MATCH "[^/]+$" sample_file ${sample})STRING(REPLACE ".cpp" "" sample_basename ${sample_file})ADD_EXECUTABLE(test_${sample_basename} ${sample})TARGET_LINK_LIBRARIES(test_${sample_basename} pthread)
ENDFOREACH()

build.sh脚本内容如下:

#! /bin/bashecho "Note: new create build directory, and executable file in build"
echo ${PWD}
mkdir -p build
cd build
cmake ..
make

执行过程:将终端定位到Linux_Code_Test/Samples_cplusplus目录下,执行:./build.sh,然后进入到build目录下,执行生成的执行文件即可。

测试结果如下:

GitHub: https://github.com/fengbingchun/Linux_Code_Test

Linux下遍历指定目录的C++实现相关推荐

  1. c++ linux下读取指定目录的所有文件名字

    总结: linux下的两个关键函数 1.     opendir()     打开一个目录 2.     readdir()     从一个目录中读取一个新的文件 windows下 读取指定目录的所有 ...

  2. c++ windows下读取指定目录的所有文件名字

    总结: windows下的两个关键函数 1.     _findfirst()     查找第一个符合规则的文件 2.     _findnext()    查找下一个符合规则的文件 linux下 读 ...

  3. [Linux C]递归遍历指定目录下的子目录和文件

    /* 功能:演示了在Linux下利用C语言递归遍历指定目录下的子目录(不含隐藏目录)和文件 */ #include <stdio.h> #include <dirent.h> ...

  4. 【文件IO】Linux 文件操作(一) —— 遍历指定目录下的所有文件

    目录 一.访问目录相关函数 1.打开/访问目录 (opendir / fdopendir) 2.读取目录内容 (readdir) 3.关闭目录 (closedir) 二.遍历指定目录下的所有文件 一. ...

  5. window和linux下遍历目录的比较

    window下,遍历目录主要是用FindFirstFile和FindNextFile,而linux下是用opendir和readdir实现 void scanFile(char *szDir) {WI ...

  6. linux下遍历目录树方法总结,linux下遍历目录树方法总结(下)

    2.使用ftw调用遍历目录 2.1ftw函数族 使用readdir函数等实现递归遍历目录树的方法比较原始,glibc2.1收录了ftw等函数,可以方便实现目录树的遍历. #include intftw ...

  7. [Linux C]递归遍历指定目录,以目录树形式展示

    /* 功能:演示了利用C语言递归遍历指定目录下的子目录(不含隐藏目录)和文件,并以目录树形式展示! 其中编译命令为:gcc -o travel travel.c -std=c99 */ #includ ...

  8. [Windowns C]递归遍历指定目录下的子目录和文件

    /* 功能:演示了利用C语言递归遍历指定目录下的子目录和文件! 说明:经修改也可以搜索文件名符合特定格式的文件,如修改"\\*.*"为"\\*.log" */ ...

  9. Java 遍历指定目录下的所有目录

    使用File类的list方法遍历指定目录下的所有目录 完整代码 import java.io.*;class Main {public static void main(String[] args) ...

最新文章

  1. 到底是先更新数据库还是先更新缓存?
  2. python利器的使用-Python数据科学利器
  3. spring4声明式事务—02 xml配置方式
  4. 从功能测试到性能测试的转型之路
  5. [转]常用数字处理算法的Verilog实现
  6. P3357 最长k可重线段集问题(网络流/串联/拆点)
  7. vuex最简单、最详细的入门文档
  8. ftp可以传输什么类型文件_FTP文件传输工具-ForkLift for Mac
  9. linux环境下安装curl,Linux环境下curl安装和移植
  10. 单元格下拉全选快捷键_复制全选快捷键是什么
  11. 【Codewars】Bouncing Balls
  12. 计算机想ping一下网络,电脑的Ping值和网络带宽之间有什么关系?
  13. 萌宠经济升温,宠物摄影师成为热门新职业-捷径系统
  14. 减少mysql存储列的方法
  15. 万兆单模模块_万兆(10G SFP+)单模光模块的介绍及应用
  16. mysql sql dateadd函数_SQL DATEADD函数 (sqlserver 只更新表中年份,不改其他时间)...
  17. 英雄杀朱雀之章在线活动
  18. 鸿蒙系统无缘华为手机,华为手机无缘鸿蒙系统!任正非隐藏锋芒,谷歌“逃过一劫”...
  19. 7行代码实现一个Tvoc/eCO2有害气体检测仪
  20. word2007添加参考文献

热门文章

  1. python-pcl GPU、输入输出模块教程翻译
  2. PCL两种方式的点云读写
  3. LabVIEW图像灰度测量(基础篇—7)
  4. 优达学城《DeepLearning》项目1:预测每日自行车租赁客流量
  5. 算法的时间与空间复杂度详解
  6. linux支持hd610显卡吗,HD610相当于什么显卡 HD610和HD630的区别 (全文)
  7. 基于Windows配置COLMAP环境
  8. python中的数据包处理模块scapy调研笔记
  9. git修改远程仓库地址
  10. 前端开发工程师面试题之综合篇