在 Linux 下用 C++ 读取目录,通常有两种常见方式:
opendir / readdir(你提到的 readdir)std::filesystem(更现代、推荐)下面分别说明。
readdir(Linux / C / C++ 通用)#include <iostream>
#include <dirent.h>
#include <cstring>
int main() {
DIR* dir = opendir("."); // 打开当前目录
if (!dir) {
perror("opendir");
return 1;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
std::cout << entry->d_name << std::endl;
}
closedir(dir);
return 0;
}
g++ readdir_example.cpp -o readdir_example
struct direntstruct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type; // DT_REG(文件) / DT_DIR(目录)
char d_name[256];
};
示例:区分文件和目录
if (entry->d_type == DT_DIR) {
std::cout << "[DIR] " << entry->d_name << std::endl;
} else {
std::cout << "[FILE] " << entry->d_name << std::endl;
}
std::filesystem(✅ 推荐)更简单、跨平台、类型安全。
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
for (const auto& entry : fs::directory_iterator(".")) {
std::cout << entry.path().filename().string();
if (fs::is_directory(entry))
std::cout << " [DIR]";
std::cout << std::endl;
}
}
编译(需要 C++17):
g++ filesystem_example.cpp -std=c++17 -o fs_example
| 特性 | readdir | std::filesystem |
|---|---|---|
| 平台 | Linux / Unix | 跨平台 |
| 复杂度 | 高 | 低 |
| 推荐度 | 底层/旧代码 | ✅ 新项目 |
✅ readdir 不是线程安全的(用 readdir_r 老接口,但现在基本不用)
✅ readdir 返回的是相对文件名,不是完整路径
✅ 遍历大目录时 std::filesystem 性能也不错
如果你有具体需求(比如递归遍历、过滤后缀、获取文件大小时间),我可以给你更完整的示例。