zl程序教程

您现在的位置是:首页 >  其他

当前栏目

stat 文件_readlink函数

文件 函数 stat
2023-06-13 09:11:03 时间

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

stat

stat函数主要用于获取文件的inode信息。 stat命令其实就是调用的stat函数。

stat中时间的辨析

  • atime(最近访问时间)
  • mtime(最近更改时间):指最近修改文件内容的时间
  • ctime(最近改动时间):指最近改动inode的时间

1)chmod 777 stat_1.txt stat之后发现ctime变了。改变了文件的权限,文件权限保存在inode里面。

2)vim stat_1.txt什么都不做,看一下退出。stat后发现atime变了。

3)echo "123456" >>stat_1.txt追加到stat_1.txt后发现mtime,ctime变了。文件内容变了mtime改变,文件大小变了ctime改变,文件大小保存在inode里面。

用法:

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

int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *path, struct stat *buf);

fstat函数获得已在描述符上打开的文件的有关信息。 lstat函数类似于stat,但是当命名的文件是一个符号连接时, lstat返回该符号连接的有关信息,而不是由该符号连接引用的文件的信息。

函数说明: 通过path获取文件信息,并保存在buf所指的结构体stat中。

返回值: 执行成功则返回0,失败返回-1,错误代码存于errno。 stat结构体:

struct stat {
    dev_t     st_dev;     /* 文件的设备编号 */
    ino_t     st_ino;     /* inode number */
    mode_t    st_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;    /* 文件字节数 */
    blksize_t st_blksize; /* blocksize for filesystem I/O */
    blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
    time_t    st_atime;   /* time of last access */
    time_t    st_mtime;   /* time of last modification */
    time_t    st_ctime;   /* time of last status change */
};

实例:

1)输出文件的大小。

#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char* argv[])
{
        struct stat s_buf;
        if(argc < 2)
        {
                printf("./app filename\n");
                exit(1);
        }
        if(stat(argv[1], &s_buf) < 0)
        {
                perror("stat");
                exit(1);
        }
        printf("%s\t%d\n", argv[1], s_buf.st_size);
        return 0;
}

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