获取文件信息

Posted on 2023-03-01 09:41  lyc2002  阅读(15)  评论(0编辑  收藏  举报

介绍

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int stat(const char *pathname, struct stat *statbuf);

struct stat {
    dev_t     st_dev;         /* ID of device containing file */
    ino_t     st_ino;         /* Inode number */
    mode_t    st_mode;        /* File type and mode */
    nlink_t   st_nlink;       /* Number of hard links */
    uid_t     st_uid;         /* User ID of owner */
    gid_t     st_gid;         /* Group ID of owner */
    dev_t     st_rdev;        /* Device ID (if special file) */
    off_t     st_size;        /* Total size, in bytes */
    blksize_t st_blksize;     /* Block size for filesystem I/O */
    blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               /* Since Linux 2.6, the kernel supports nanosecond
                  precision for the following timestamp fields.
                  For the details before Linux 2.6, see NOTES. */

    struct timespec st_atime;  /* Time of last access */
    struct timespec st_mtime;  /* Time of last modification */
    struct timespec st_ctime;  /* Time of last status change */
};

功能:获取文件相关信息

参数:

  • pathname:文件路径
  • statbuf:传出参数,用于保存获取的文件信息

返回值:

  • 成功返回 0
  • 失败返回 -1,并设置 errno

简单使用

char *real_file = "./test.txt";
struct stat file_stat;

// 判断文件是否存在
if (stat(real_file, &file_stat) < 0) {
    printf("no resource\n");
}

// 判断文件是否可读
if (!(file_stat.st_mode & S_IROTH)) {
    printf("forbidden request\n");
}

// 判断文件类型是否是目录
if (S_ISDIR(sile_stat.st_mode)) {
    printf("bad request\n");
}

注意事项