详解C/C++如何获取路径下所有文件及其子目录的文件名?

一、功能描述

需要提取某个文件夹下所有文件名字,当包含子目录时,将子目录及其路径获取到。

二、实现方式

使用C语言的opendir函数

  DIR* dp;
  struct dirent* dirp;
  if ((dp = opendir(sdir.c_str())) != NULL) {
      dirp = readdir(dp)
  }

通过readir读取到的dirp中包含的d_type具有如下类型及其含义:

enum
  {
    DT_UNKNOWN = 0,
# define DT_UNKNOWN    DT_UNKNOWN
    DT_FIFO = 1,
# define DT_FIFO    DT_FIFO
    DT_CHR = 2,
# define DT_CHR        DT_CHR
    DT_DIR = 4,
# define DT_DIR        DT_DIR
    DT_BLK = 6,
# define DT_BLK        DT_BLK
    DT_REG = 8,
# define DT_REG        DT_REG
    DT_LNK = 10,
# define DT_LNK        DT_LNK
    DT_SOCK = 12,
# define DT_SOCK    DT_SOCK
    DT_WHT = 14
# define DT_WHT        DT_WHT
  };

参考官方文档可知

DT_UNKNOWN ¶

The type is unknown. Only some filesystems have full support to return the type of the file, others might always return this value.

未知类型

DT_REG

A regular file. 常规文件

DT_DIR

A directory. 目录

DT_FIFO

A named pipe, or FIFO. See FIFO Special Files.

DT_SOCK

A local-domain socket. 套接字文件

DT_CHR

A character device. 字符设备

DT_BLK

A block device. 块设备,比如挂载的硬盘之类

DT_LNK

A symbolic link. 链接文件

三、代码实现

通过递归的方式,获取该目录及其子目录下的所有文件及其路径名

#include <dirent.h>
#include <vector>
/**
 * @brief GetFiles: 获取文件夹内的所有文件名字
 * @param sdir
 * @param bsubdir: true 包含子目录下的文件
 * @return
 */
std::vector<std::string> GetFiles(const std::string& sdir = ".",
                                  bool bsubdir = true) {
  DIR* dp;
  struct dirent* dirp;
  std::vector<std::string> filenames;
  if ((dp = opendir(sdir.c_str())) != NULL) {
    while ((dirp = readdir(dp)) != NULL) {
      if (strcmp(".", dirp->d_name) == 0 || strcmp("..", dirp->d_name) == 0)
        continue;
      if (dirp->d_type != DT_DIR)
        filenames.push_back(sdir + "/" + dirp->d_name);
      if (bsubdir && dirp->d_type == DT_DIR) {
        std::vector<std::string> names = GetFiles(sdir + "/" + dirp->d_name);
        filenames.insert(filenames.begin(), names.begin(), names.end());
      }
    }
  }
  closedir(dp);
  return filenames;
}

原文地址:https://blog.csdn.net/Q_upup/article/details/129486406