struct stat 结构体

核心概念

在 C++(和 C)中,stat 是一个用于获取文件状态信息的系统调用和函数,它填充一个 struct stat 结构体,其中包含文件的元数据(metadata)。这个功能对于文件操作至关重要

构成

struct stat {
    dev_t     st_dev;        // 文件所在设备的 ID
    ino_t     st_ino;        // Inode 编号(唯一标识文件)
    mode_t    st_mode;       // 文件类型和权限
    nlink_t   st_nlink;      // 硬链接数量
    uid_t     st_uid;        // 所有者用户 ID
    gid_t     st_gid;        // 所有者组 ID
    dev_t     st_rdev;       // 设备文件的设备 ID
    off_t     st_size;       // 文件大小(字节)
    blksize_t st_blksize;    // 文件系统 I/O 块大小
    blkcnt_t  st_blocks;     // 分配的磁盘块数量

    // 时间戳(现代系统使用纳秒精度)
    struct timespec st_atim; // 最后访问时间
    struct timespec st_mtim; // 最后修改时间(内容)
    struct timespec st_ctim; // 最后状态变更时间(元数据)
};

相关函数

#include <sys/stat.h>  // 必需头文件

int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);
  • stat():通过文件路径获取信息(会跟随符号链接)
  • fstat():通过文件描述符获取文件信息
  • lstat():通过文件路径获取信息(不会跟随符号)

常用宏定义(文件类型判断)

image

posted @ 2025-07-20 11:03  北燃  阅读(49)  评论(0)    收藏  举报