在 Ubuntu(Linux)下,使用 C 语言进行目录操作时,opendir 和 readdir 通常是成对使用的:
opendir:打开一个目录,返回 DIR *readdir:从 DIR * 中逐个读取目录项(struct dirent)下面给你一个完整、常见用法示例,并解释关键点。
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
if (argc < 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
opendir()
↓
DIR *
↓
readdir() ← 循环调用
↓
struct dirent *
↓
closedir()
struct dirent {
ino_t d_ino; // inode 号
off_t d_off; // 偏移
unsigned short d_reclen; // 记录长度
unsigned char d_type; // 文件类型
char d_name[256]; // 文件名
};
DT_REG 普通文件
DT_DIR 目录
DT_LNK 符号链接
示例:只列出目录
if (entry->d_type == DT_DIR) {
printf("DIR: %s\n", entry->d_name);
}
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
#include <sys/stat.h>
char path[512];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
struct stat st;
stat(path, &st);
if (S_ISDIR(st.st_mode)) {
// 递归处理
}
if (readdir(dir) == NULL && errno != 0) {
perror("readdir");
}
gcc dir_list.c -o dir_list
./dir_list /tmp
opendir 打开目录,readdir 循环读取,closedir 关闭目录
如果你需要:
readdir_r(线程安全)可以直接告诉我。