首页 > 系统相关 >Linux系统编程09-stat和lstat

Linux系统编程09-stat和lstat

时间:2022-10-14 22:25:27浏览次数:46  
标签:文件 stat lstat 09 statbuf st time include


    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    
    int stat(const char *pathname, struct stat *statbuf);
        作用: 获取一个文件相关的一些信息, 
            如果去获取一个软连接,那么获取的是指向的文件的信息
        参数:
            - pathname: 操作的文件的路径
            - statbuf: 结构体变量,传出参数,用于保存获取到的文件信息
        返回值:
            成功: 0
            失败: -1, 设置errno
    
    int lstat(const char *pathname, struct stat *statbuf);
        作用: 获取软连接文件本身的信息,而不是指向文件的信息
        参数:
            - pathname: 操作的文件的路径
            - statbuf: 结构体变量,传出参数,用于保存获取到的文件信息
        返回值:
            成功: 0
            失败: -1, 设置errno
    
    stat 结构体:
    struct stat {
        dev_t st_dev; // 文件的设备编号
        ino_t st_ino; // 节点
        mode_t st_mode; // 文件的类型和存取的权限
        nlink_t st_nlink; // 连到该文件的硬连接数目
        uid_t st_uid; // 用户ID
        gid_t  st_gid; // 组ID
        dev_t st_rdev; // 设备文件的设备编号
        off_t st_size; // 文件字节数(文件大小)
        blksize_t st_blksize; // 块大小
        blkcnt_t st_blocks; // 块数
        time_t st_atime; // 最后一次访问时间
        time_t st_mtime; // 最后一次修改时间
        time_t st_ctime; // 最后一次改变时间(指属性)
    };

实例:获取文件信息

stat.c

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

int main(int argc, char const *argv[])
{
    struct stat statbuf;
    int ret = stat("hello.txt", &statbuf);
    if (ret == -1)
    {
        perror("stat err");
        return -1;
    }

    struct tm t;
    char date_time[64];
    strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localtime_r(&statbuf.st_atim.tv_sec, &t));
    printf("size: %ld\n", statbuf.st_size);
    printf("second: %ld\n", statbuf.st_atim.tv_sec);
    printf("date: %s\n", date_time);
    return 0;
}

size: 112
second: 1665735924
date: 2022-10-14 16:25:24

标签:文件,stat,lstat,09,statbuf,st,time,include
From: https://www.cnblogs.com/anqwjoe/p/16793190.html

相关文章