在 Ubuntu(Linux)下使用 C/C++ 的 opendir 来打开一个目录并遍历文件,需要包含 <dirent.h>。下面是一个清晰、常用的示例。
#include <iostream>
#include <dirent.h>
#include <cstring>
int main() {
DIR* dir = opendir("."); // 打开当前目录
if (dir == nullptr) {
perror("opendir");
return 1;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
std::cout << entry->d_name << std::endl;
}
closedir(dir);
return 0;
}
. 和 ..)#include <iostream>
#include <dirent.h>
int main() {
DIR* dir = opendir("/tmp");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_REG) { // 普通文件
std::cout << entry->d_name << std::endl;
}
}
closedir(dir);
return 0;
}
stat 判断文件类型(更通用)#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
int main() {
DIR* dir = opendir(".");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr) {
struct stat st;
if (stat(entry->d_name, &st) == 0) {
if (S_ISREG(st.st_mode)) {
std::cout << entry->d_name << " (file)" << std::endl;
} else if (S_ISDIR(st.st_mode)) {
std::cout << entry->d_name << " (dir)" << std::endl;
}
}
}
closedir(dir);
return 0;
}
g++ opendir_example.cpp -o opendir_example
./opendir_example
opendir 返回 DIR*closedir 关闭. 和 .. 也会出现d_type 在某些文件系统(如 NFS)可能不可靠,建议用 stat如果你可以用 C++17:
#include <filesystem>
namespace fs = std::filesystem;
for (auto& p : fs::directory_iterator(".")) {
std::cout << p.path() << std::endl;
}
编译:
g++ main.cpp -std=c++17 -lstdc++fs
如果你有具体需求(比如递归遍历、过滤后缀、读取权限等),可以告诉我。