Linux系统编程-stat函数

stat函数

stat的用法

第一个参数是获取的文件属性的名字,第二个参数是结构体指针。

将pathname指针指向的文件属性信息,填到statbuf中。

stat的返回值

成功返回0。失败返回-1,并生成errno。

struct stat结构体

struct stat
{
    dev_t     st_dev;     /* ID of device containing file */文件使用的设备号
    ino_t     st_ino;     /* inode number */    索引节点号 
    mode_t    st_mode;    /* protection */  文件对应的模式,文件,目录等
    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; /* blocksize for file system 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 */ 最后一次改变该文件状态的时间   
};

代码

将fname指针指向的文件属性信息,填到statres中。根据struct stat结构体,调用st_size的返回值为off_t。

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

static off_t flen(const char *fname)
{
    struct stat statres;

    if (stat(fname, &statres) < 0)
    {
	    perror("stat()");
	    exit(1);
    }
    
    return statres.st_size;
}

int main(int argc, char **argv)
{
     if(argc < 2) {
        fprintf(stderr, "Usage...\n");
	    exit(1);
     }

     printf("%lld\n", (long long)flen(argv[1]));
     exit(0);
}

修改makefile文件,vim makefile

运行flen.c

查看flen.c文件大小为458

传入参数flen.c,结果为458

参考链接

stat函数详解-CSDN博客

  • 21
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值