在 Linux 下使用 C/C++ 读取目录,readdir 是 POSIX 标准库提供的函数,配合 opendir / closedir 使用。下面给你一个完整、常见、可直接用的示例。
#include <iostream>
#include <dirent.h>
#include <cstring>
#include <sys/types.h>
#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;
}
opendirDIR* opendir(const char* path);
NULLreaddirstruct dirent* readdir(DIR* dirp);
NULLstruct dirent 常用字段struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_rendtl;
unsigned char d_type;
char d_name[256];
};
常用:
d_name:文件名d_type:文件类型(可选). 和 ..while ((entry = readdir(dir)) != nullptr) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
std::cout << entry->d_name << std::endl;
}
#include <sys/stat.h>
while ((entry = readdir(dir)) != nullptr) {
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode))
std::cout << "[DIR] ";
else
std::cout << "[FILE] ";
std::cout << entry->d_name << std::endl;
}
如果你可以用 C++17:
#include <filesystem>
namespace fs = std::filesystem;
for (auto& p : fs::directory_iterator(".")) {
std::cout << p.path().filename() << std::endl;
}
✅ 更安全、跨平台
❌ 需要 -std=c++17 -lstdc++fs(老版本 GCC)
g++ readdir_example.cpp -o readdir_example
如果你有具体需求(比如递归遍历目录、只找某种文件、统计大小),可以告诉我,我给你更针对性的代码。