温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C/C++怎么获取路径下所有文件及其子目录的文件名

发布时间:2023-03-14 14:10:06 来源:亿速云 阅读:391 作者:iii 栏目:开发技术

这篇文章主要介绍了C/C++怎么获取路径下所有文件及其子目录的文件名的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇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;
}

关于“C/C++怎么获取路径下所有文件及其子目录的文件名”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C/C++怎么获取路径下所有文件及其子目录的文件名”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++ c
AI