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;
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值