在 Debian(其实任何 Linux 系统都通用)下,opendir 是用来打开目录,而不是读取文件内容的。
如果你想“读取目录中的文件”,一般流程是:
opendir 打开目录readdir 读取目录项(文件名)open / fopen 去读取具体文件内容#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("/tmp");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("文件名: %s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 这样可以列出目录里的所有文件名
❌ 但还没有读取文件内容
#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir = opendir("/tmp");
struct dirent *entry;
char path[256];
FILE *fp;
char buf[1024];
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "/tmp/%s", entry->d_name);
fp = fopen(path, "r");
if (!fp) continue;
printf("=== %s ===\n", path);
while (fgets(buf, sizeof(buf), fp)) {
printf("%s", buf);
}
fclose(fp);
}
closedir(dir);
return 0;
}
❌ opendir 不能读取文件
✅ opendir → readdir → open/fopen
如果你想要:
open() / fopen()opendir + readdir + fopengcc test.c -o test
./test
如果你是想:
可以告诉我,我可以给你对应版本。