在 Ubuntu(Linux)下,使用 C/C++ 读取目录通常配合 opendir + readdir 一起使用,流程很固定。下面给你一个完整说明和示例。
#include <dirent.h>
#include <stdio.h>
DIR *dir = opendir("目录路径");
if (dir == NULL) {
perror("opendir");
return -1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
opendirDIR *opendir(const char *name);
DIR* 指针NULLreaddirstruct dirent *readdir(DIR *dirp);
struct dirent *NULLclosedirint closedir(DIR *dirp);
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译运行:
gcc readdir_example.c -o readdir_example
./readdir_example /home
struct dirent 常用字段struct dirent {
ino_t d_ino; // inode 号
off_t d_off;
unsigned short d_reclen;
unsigned char d_type; // 文件类型
char d_name[256];
};
if (entry->d_type == DT_REG) // 普通文件
if (entry->d_type == DT_DIR) // 目录
✅ 会读到:
.(当前目录)..(上级目录)如需过滤:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
✅ 不是递归的(只列当前目录)
可以用:
readdir + 递归调用nftw()(更专业)如果你愿意,我可以给你:
std::filesystem)直接说你的使用场景即可。