在C/C++编程中,获取指定路径下的文件名及子目录中的文件名是一项常见的任务,无论是处理文件系统,还是进行文件操作,这个功能都显得尤为重要。通过使用递归的方法,我们可以轻松地获取指定路径下的所有文件及子目录的文件名。在这个过程中,我们可以利用一些系统提供的API函数来完成这个任务,如FindFirstFile和FindNextFile等。通过编写递归函数,我们可以遍历指定路径下的所有文件及子目录,将它们的文件名存储起来并进行相应的操作。接下来我们将探讨如何使用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_REGA regular file. 常规文件DT_DIRA directory. 目录DT_FIFOA named pipe, or FIFO. See FIFO Special Files.DT_SOCKA local-domain socket. 套接字文件DT_CHRA character device. 字符设备DT_BLKA block device. 块设备,比如挂载的硬盘之类DT_LNKA 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++获取路径下文件文件名内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
以上是获取路径下文件名的全部内容,如果您遇到这种情况,可以按照以上方法解决,希望对大家有所帮助。
相关教程
2023-11-27
2023-09-07
2023-07-04
2023-07-17
2024-03-29
2023-07-04
2023-11-03
2023-07-27
2023-07-26
2024-01-11
2024-12-19
2024-11-20
2024-11-10
2024-11-01
2024-10-28
2024-10-27