在 Ubuntu(Linux)下,opendir 和 readdir 通常是配对使用的,用来遍历目录中的文件和子目录。它们都来自 <dirent.h>。
下面给你一个清晰的使用流程和示例。
#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);
#include <stdio.h>
#include <dirent.h>
int main() {
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);
return 0;
}
编译运行:
gcc test.c -o test
./test
. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
stat)#include <sys/stat.h>
struct stat st;
char path[256];
snprintf(path, sizeof(path), "%s/%s", dirname, entry->d_name);
stat(path, &st);
if (S_ISDIR(st.st_mode)) {
printf("[目录] %s\n", entry->d_name);
} else {
printf("[文件] %s\n", entry->d_name);
}
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
char full[512];
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
printf("%s\n", full);
struct stat st;
stat(full, &st);
if (S_ISDIR(st.st_mode))
list_dir(full);
}
closedir(dir);
}
❌ 忘记 closedir
❌ 直接用 entry->d_type(在某些文件系统上不可靠)
❌ 路径不存在导致 opendir 返回 NULL
opendir 打开目录,readdir 逐个读取目录项,closedir 关闭目录
如果你是想做:
ls -R可以继续问我,我可以给你对应示例。