c++指定一个路径,遍历路径下所有文件和目录,并输出文件和目录的名称
时间: 2024-02-04 12:03:15 浏览: 156
好的,可以使用C++的`<dirent.h>`标准库来实现。以下是一个示例代码:
```c++
#include <iostream>
#include <dirent.h>
#include <string>
void traverseDirectory(const std::string& path) {
DIR* dir = opendir(path.c_str());
if (dir == nullptr) {
std::cerr << "Failed to open directory: " << path << std::endl;
return;
}
dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] == '.') {
continue; // 忽略当前目录和上级目录
}
std::string entryPath = path + "/" + entry->d_name;
if (entry->d_type == DT_DIR) {
std::cout << "Directory: " << entryPath << std::endl;
traverseDirectory(entryPath); // 递归遍历子目录
} else if (entry->d_type == DT_REG) {
std::cout << "File: " << entryPath << std::endl;
}
}
closedir(dir);
}
int main() {
// 指定路径
std::string path = "/path/to/directory";
// 遍历路径下所有文件和目录
traverseDirectory(path);
return 0;
}
```
你可以将代码中的`path`变量替换为你想要遍历的路径,然后编译并运行代码即可输出该路径下所有文件和目录的名称。需要注意的是,`<dirent.h>`标准库是POSIX标准库,如果你在Windows平台上编译代码,可能需要使用Windows API的相关函数来实现。
阅读全文
相关推荐


















