在 CentOS(Linux) 下,使用 C 语言通过 readdir 读取目录,一般流程是:
opendir() 打开目录readdir() 循环读取目录项closedir() 关闭目录#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
if (argc < 2) {
printf("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;
}
gcc readdir_test.c -o readdir_test
./readdir_test /etc
struct dirent 常用字段struct dirent {
ino_t d_ino; // inode 号
off_t d_off; // 偏移量
unsigned short d_reclen; // 记录长度
unsigned char d_type; // 文件类型
char d_name[256];// 文件名
};
d_type 值| 宏 | 含义 |
|---|---|
| DT_REG | 普通文件 |
| DT_DIR | 目录 |
| DT_LNK | 符号链接 |
| DT_UNKNOWN | 未知 |
示例:只列出目录
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;
readdir 只给文件名,要详细信息需用 stat():
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
printf("size: %ld\n", st.st_size);
确保终端是 UTF-8:
locale
使用 sudo 或确保目录可读。
如果你需要:
可以继续问我。