在 Ubuntu(Linux) 下,opendir 是用来打开目录流的函数,属于 POSIX 标准,在 <dirent.h> 里。
下面给你一个完整、常用、正确的写法示例。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, char *argv[])
{
const char *path = "."; // 当前目录
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return EXIT_SUCCESS;
}
gcc opendir_demo.c -o opendir_demo
./opendir_demo
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) {
printf("普通文件: %s\n", entry->d_name);
} else if (entry->d_type == DT_DIR) {
printf("目录: %s\n", entry->d_name);
}
⚠️
d_type在某些文件系统(如 NFS)上可能不可用,稳妥方式用lstat()。
DIR dir; // ❌ 错误,DIR 是指针类型
opendir(path); // ❌ 不检查返回值
✅ 正确方式:
DIR *dir = opendir(path);
if (!dir) { ... }
void list_dir(const char *path)
{
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
struct dirent *ent;
while ((ent = readdir(dir))) {
puts(ent->d_name);
}
closedir(dir);
}
如果你需要:
可以直接告诉我,我可以给你更贴近你需求的代码。