详解C/C++如何获取路径下所有文件及其子目录的文件名
目录
- 一、功能描述
- 二、实现方式
- 三、代码实现
一、功能描述
需要提取某个文件夹下所有文件名字,当包含子目录时,将子目录及其路径获取到。
二、实现方式
使用C语言的opendir函数
DIR* javascriptdp;
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_FIF编程OA 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 || strhttp://www.devze.comcmp("..", dirp->d_name) == 0)
javascript 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++获取路径下文件开发者_Python入门文件名内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
加载中,请稍侯......
精彩评论