在 Ubuntu(Linux)上,opendir 可以用于 C++,因为 C++ 可以调用 C 标准库和 POSIX 接口。
opendir 是什么opendir 是 POSIX 标准函数,声明在:
#include <dirent.h>
原型:
DIR *opendir(const char *name);
它用于打开一个目录,配合 readdir、closedir 使用。
C++ 完全兼容 C,所以可以直接用:
#include <iostream>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != nullptr) {
std::cout << entry->d_name << std::endl;
}
closedir(dir);
return 0;
}
编译:
g++ test.cpp -o test
如果你用的是 C++17 及以上,更推荐用标准库:
#include <filesystem>
#include <iostream>
int main() {
for (const auto &p : std::filesystem::directory_iterator(".")) {
std::cout << p.path() << std::endl;
}
}
编译(Ubuntu 旧版本可能需要):
g++ test.cpp -o test -std=c++17 -lstdc++fs
(Ubuntu 20.04+ 一般不需要 -lstdc++fs)
opendir 可以在 Ubuntu 的 C++ 中使用std::filesystem如果你需要 递归遍历目录 或 过滤文件类型 的示例,也可以告诉我。