在 Ubuntu(Linux)下使用 C 语言编程时,opendir 本身只能打开目录,并不能直接“获取文件”。
正确的流程是:
opendir → readdir → 判断是否是文件 → 获取文件信息
#include <dirent.h>
DIR *dir = opendir("/path/to/dir");
if (dir == NULL) {
perror("opendir");
return -1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("name: %s\n", entry->d_name);
}
⚠️
readdir返回的是 目录项,包括:
- 普通文件
- 子目录
- 符号链接
.和..
stat(最常用 ✅)#include <sys/stat.h>
struct stat st;
char path[256];
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "%s/%s", "/path/to/dir", entry->d_name);
if (stat(path, &st) == -1)
continue;
if (S_ISREG(st.st_mode)) {
printf("文件: %s\n", entry->d_name);
}
}
| 宏 | 含义 |
|---|---|
S_ISREG(m) |
普通文件 |
S_ISDIR(m) |
目录 |
S_ISLNK(m) |
符号链接 |
d_type(更快,但不一定全支持)while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) {
printf("文件: %s\n", entry->d_name);
}
}
⚠️ 某些文件系统(如某些网络文件系统)
d_type可能是DT_UNKNOWN
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir = opendir(".");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
char path[512];
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "./%s", entry->d_name);
struct stat st;
if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
printf("文件: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
❌ 以为 opendir 能直接拿到文件内容
✅ opendir 只是打开目录,文件内容要用 open/read
❌ 忘记过滤 . 和 ..
✅ 必须手动跳过
如果你需要:
告诉我,我可以直接给你代码。