关于stat、struct stat 的知识、用法

今天看代码的时候遇到struct stat这个结构体,以前没见过。。在网上查了一下,普及知识and备忘。

定义函数:    int stat(const char *file_name, struct stat *buf);
函数功能:    通过文件名filename获取文件信息,并保存在buf所指的结构体stat中;
返 回 值  :    执行成功则返回0,失败返回-1,错误代码存于errno。

还有两个函数也差不多的:

int fstat(int filedes, struct stat *buf);//通过文件描述符获取文件对应的属性。
int lstat(const char *restrict pathname, struct stat *restrict buf);//连接文件描述命,获取文件属性。2 文件对应的属性。

三个函数都属于系统调用。

结构体 

struct stat
{
    dev_t       st_dev;     /* ID of device containing file -文件所在设备的ID*/
    ino_t       st_ino;     /* inode number -inode节点号*/
    mode_t      st_mode;    /* protection -保护模式 文件的类型和存取的权限*/
    nlink_t     st_nlink;   /* number of hard links -链向此文件的连接数(硬连接)*/
    uid_t       st_uid;     /* user ID of owner -user id 所属用户ID*/
    gid_t       st_gid;     /* group ID of owner - group id 组ID*/
    dev_t       st_rdev;    /* device ID (if special file) -设备号,针对设备文件*/
    off_t       st_size;    /* total size, in bytes -文件大小,字节为单位*/
    blksize_t   st_blksize; /* blocksize for filesystem I/O -系统块的大小*/
    blkcnt_t    st_blocks;  /* number of 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 - */
};

自己写个stat_test.c如下:

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include<errno.h>
#define TESTFILE "./stat_test.c"
int print_stat(struct stat *ptr)
{
        printf("the file of '%s' status info :\n",TESTFILE);
        printf("The major device no is:%d\n",major(ptr->st_dev));//主设备号
        printf("The minor device no is:%d\n",minor(ptr->st_dev));//从设备号
        printf("The file's node number is:%d\n",ptr->st_ino);//文件节点号
        printf("The file's access mode is:%d\n",ptr->st_mode);//文件的访问模式
        printf("The file's hard link number is:%d\n",ptr->st_nlink);//文件的硬链接数目
        printf("The file's user id is:%d\n",ptr->st_uid);//文件拥有者的ID
        printf("The file's group id is:%d\n",ptr->st_gid);//文件的组ID
        printf("The file's size is:%d\n",ptr->st_size);//文件的大小
        printf("The block size is:%d\n",ptr->st_blksize);//文件占用的块数量
        printf("The number of allocated blocks is:%d\n",ptr->st_blocks);//文件分配块数量
        return 0;
}

int main(int argc, char **argv)
{
        struct stat status;
        int rt_stat;
        rt_stat=stat(TESTFILE, &status);//获取文件TESTFILE的状态信息,填入status中
        if(rt_stat < 0){
                perror("Error:stat failed");
                return -1;
        }
        print_stat(&status);
        return 0;
}
编译及结果:

其实这个函数也是主要用于限定一些文件的大小,比如日志的大小不能超过多少k等。。。

e.g...

if(ptr->st_size > 0x4000)//如果文件大于16K

{

//do something。。。

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值