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

其他教程   发布日期:2023年08月27日   浏览次数:430

这篇文章主要介绍了C/C++怎么获取路径下所有文件及其子目录的文件名的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C/C++怎么获取路径下所有文件及其子目录的文件名文章都会有所收获,下面我们一起来看看吧。

一、功能描述

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

二、实现方式

使用C语言的opendir函数

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

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

  1. enum
  2. {
  3. DT_UNKNOWN = 0,
  4. # define DT_UNKNOWN DT_UNKNOWN
  5. DT_FIFO = 1,
  6. # define DT_FIFO DT_FIFO
  7. DT_CHR = 2,
  8. # define DT_CHR DT_CHR
  9. DT_DIR = 4,
  10. # define DT_DIR DT_DIR
  11. DT_BLK = 6,
  12. # define DT_BLK DT_BLK
  13. DT_REG = 8,
  14. # define DT_REG DT_REG
  15. DT_LNK = 10,
  16. # define DT_LNK DT_LNK
  17. DT_SOCK = 12,
  18. # define DT_SOCK DT_SOCK
  19. DT_WHT = 14
  20. # define DT_WHT DT_WHT
  21. };

参考官方文档可知

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. 链接文件

三、代码实现

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

  1. #include <dirent.h>
  2. #include <vector>
  3. /**
  4. * @brief GetFiles: 获取文件夹内的所有文件名字
  5. * @param sdir
  6. * @param bsubdir: true 包含子目录下的文件
  7. * @return
  8. */
  9. std::vector<std::string> GetFiles(const std::string& sdir = ".",
  10. bool bsubdir = true) {
  11. DIR* dp;
  12. struct dirent* dirp;
  13. std::vector<std::string> filenames;
  14. if ((dp = opendir(sdir.c_str())) != NULL) {
  15. while ((dirp = readdir(dp)) != NULL) {
  16. if (strcmp(".", dirp->d_name) == 0 || strcmp("..", dirp->d_name) == 0)
  17. continue;
  18. if (dirp->d_type != DT_DIR)
  19. filenames.push_back(sdir + "/" + dirp->d_name);
  20. if (bsubdir && dirp->d_type == DT_DIR) {
  21. std::vector<std::string> names = GetFiles(sdir + "/" + dirp->d_name);
  22. filenames.insert(filenames.begin(), names.begin(), names.end());
  23. }
  24. }
  25. }
  26. closedir(dp);
  27. return filenames;
  28. }

以上就是C/C++怎么获取路径下所有文件及其子目录的文件名的详细内容,更多关于C/C++怎么获取路径下所有文件及其子目录的文件名的资料请关注九品源码其它相关文章!