在Linux环境下使用C++遍历目录,通常会用到<dirent.h>
库中的opendir
、readdir
和closedir
函数。以下是一个简单的示例代码,展示了如何遍历指定目录下的所有文件和子目录:
#include <iostream>
#include <string>
#include <dirent.h>
#include <sys/types.h>
void listFiles(const std::string& path) {
DIR* dir;
struct dirent* entry;
if ((dir = opendir(path.c_str())) != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
std::cout << entry->d_name << std::endl;
}
closedir(dir);
} else {
std::cerr << "无法打开目录: " << path << std::endl;
}
}
int main() {
std::string directoryPath = "/path/to/directory"; // 替换为你要遍历的目录路径
listFiles(directoryPath);
return 0;
}
opendir
: 打开一个目录流。readdir
: 读取目录流中的下一个目录项。closedir
: 关闭目录流。opendir
会返回nullptr
。#include <iostream>
#include <string>
#include <dirent.h>
#include <sys/types.h>
void listFilesRecursively(const std::string& path) {
DIR* dir;
struct dirent* entry;
if ((dir = opendir(path.c_str())) != nullptr) {
while ((entry = readdir(dir)) != nullptr) {
std::string name = entry->d_name;
if (name != "." && name != "..") {
std::string fullPath = path + "/" + name;
if (entry->d_type == DT_DIR) {
listFilesRecursively(fullPath);
} else {
std::cout << fullPath << std::endl;
}
}
}
closedir(dir);
} else {
std::cerr << "无法打开目录: " << path << std::endl;
}
}
int main() {
std::string directoryPath = "/path/to/directory"; // 替换为你要遍历的目录路径
listFilesRecursively(directoryPath);
return 0;
}
通过这种方式,你可以有效地遍历Linux系统中的目录结构,并根据需要进行相应的处理。