温馨提示×

debian copendir怎么配合stat用

小樊
49
2026-10-01 02:51:02
栏目: 智能运维

在 Debian(以及其它 Linux 系统)里,opendir 是 C 语言里用来打开目录的函数,而 stat 是用来获取文件/目录属性的函数。通常的配合方式是:

用 opendir + readdir 遍历目录,再用 stat(或 lstat)获取每个文件的详细信息。

下面给你一个完整、常见的示例。


基本流程

  1. opendir() 打开目录
  2. readdir() 逐个读取目录项
  3. 对每个目录项调用 stat()
  4. 从 struct stat 中读取信息
  5. 最后 closedir()

示例:列出目录下所有文件及其大小

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "用法: %s <目录>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    if (!dir) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    char path[1024];
    struct stat st;

    while ((entry = readdir(dir)) != NULL) {
        // 跳过 . 和 ..
        if (strcmp(entry->d_name, ".") == 0 ||
            strcmp(entry->d_name, "..") == 0)
            continue;

        snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

        if (stat(path, &st) == -1) {
            perror("stat");
            continue;
        }

        printf("%s\t大小: %ld 字节\n", entry->d_name, st.st_size);
    }

    closedir(dir);
    return 0;
}

编译(Debian)

gcc dir_stat.c -o dir_stat
./dir_stat /tmp

stat vs lstat

函数 特点
stat() 会跟随符号链接
lstat() 不会跟随符号链接(适合处理软链)

如果你要处理符号链接,建议用:

lstat(path, &st);

然后判断:

S_ISLNK(st.st_mode)

常见 stat 字段

st.st_size      // 文件大小
st.st_mode      // 文件类型和权限
st.st_mtime     // 修改时间
st.st_uid       // 所属用户
st.st_gid       // 所属组

判断文件类型:

S_ISREG(st.st_mode)  // 普通文件
S_ISDIR(st.st_mode)  // 目录

小结

✅ opendir 负责“进目录”
✅ readdir 负责“挨个看”
✅ stat 负责“看详情”

如果你是想 在 shell 里用 opendir 类似的思路(比如 find + stat),我也可以给你命令行版本。

0 踩