zl程序教程

您现在的位置是:首页 > 

当前栏目

stat函数的使用说明[通俗易懂]

使用 函数 通俗易懂 说明 stat
2023-06-13 09:11:03 时间

大家好,又见面了,我是你们的朋友全栈君。

1:stat函数

取得指定文件的文件属性,文件属性存储在结构体stat里

#include <sys/stat.h>
int stat(const char *pathname, struct stat *statbuf);

2:结构体stat

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_atim;  /* Time of last access */
               struct timespec st_mtim;  /* Time of last modification */
               struct timespec st_ctim;  /* Time of last status change */

           #define st_atime st_atim.tv_sec /* Backward compatibility */
           #define st_mtime st_mtim.tv_sec
           #define st_ctime st_ctim.tv_sec
           };

st_dev:设备ID,不太常用

st_ino:【inode】,【inode】是啥?不知道就看上面关于【inode】的解释

st_mode:文件的类型和权限,共16位,如下图。

0-11位控制文件的权限

12-15位控制文件的类型

0-2比特位:其他用户权限

3-5比特位:组用户权限

6-8比特位:本用户权限

9-11比特位:特殊权限

12-15比特位:文件类型(因为文件类型只有7中,所以用12-14位就够

文件类型的宏如下(下面的数字是8进制):

S_IFSOCK 0140000 socket S_IFLNK 0120000 symbolic link(软连接) S_IFREG 0100000 regular file(普通文件) S_IFBLK 0060000 block device(块设备文件) S_IFDIR 0040000 directory(目录) S_IFCHR 0020000 character device(字符设备文件) S_IFIFO 0010000 FIFO(管道) st_nlink:硬连接计数

st_uid:这个文件所属用户的ID

st_gid:这个文件所属用户的组ID

st_rdev:特殊设备的ID,不太常用

st_size:文件的大小

st_blksize:不明是干啥的

st_blocks:不明是干啥的

struct timespec st_atim:最后访问的时间

struct timespec st_mtim:最后修改的时间

struct timespec st_ctim:最后状态改变的时间

3:示例

/************************************************************************* > File Name: stat.c > Author: kayshi > Mail: kayshi2019@qq.com > Created Time: Sat 17 Oct 2020 04:13:17 PM CST ************************************************************************/

#include <stdio.h>
#include <sys/stat.h>

#define FILE_N "/home/kayshi/code/Test/test.txt"

void main(void)
{ 
   
    struct stat file_stat;

    stat(FILE_N, &file_stat);
    printf("%ld", file_stat.st_size);
}

获得文件text.txt的大小

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/171796.html原文链接:https://javaforall.cn