struct stat 作用

stat,lstat,fstat1 函数都是获取文件(普通文件,目录,管道,socket,字符,块()的属性。函数原型#include <sys/stat.h>

int stat(const char *restrict pathname, struct stat *restrict buf);提供文件名字,获取文件对应属性。

int fstat(int filedes, struct stat *buf);通过文件描述符获取文件对应的属性。

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

struct stat {

        mode_t     st_mode;       //文件对应的模式,文件,目录等

        ino_t      st_ino;       //inode节点号

        dev_t      st_dev;        //设备号码

        dev_t      st_rdev;       //特殊设备号码

        nlink_t    st_nlink;      //文件的连接数

        uid_t      st_uid;        //文件所有者

        gid_t      st_gid;        //文件所有者对应的组

        off_t      st_size;       //普通文件,对应的文件字节数

        time_t     st_atime;      //文件最后被访问的时间

        time_t     st_mtime;      //文件内容最后被修改的时间

        time_t     st_ctime;      //文件状态改变时间

        blksize_t st_blksize;    //文件内容对应的块大小

        blkcnt_t   st_blocks;     //伟建内容对应的块数量

      };

----------------------------------------------------------------------------------------

#include <unsitd.h>

#inlcude <sys/stat.h>

#include <sys/types.h>

int fstat(int filedes,struct stat *buf);

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

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

这三个系统调用都可以返回指定文件的状态信息,这些信息被写到结构struct stat的缓冲区中。通过分析这个结构可以获得指定文件的信息。

void report(struct stat *ptr)

{

     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->uid);//文件拥有者的ID

     printf("The file's group id is:%d\n",ptr->gid);//文件的组ID

     printf("The file's size is:%d\n",ptr->st_size);//文件的大小

     printf("The block size is:%d\n",ptr->blksize);//文件占用的块数量

     printf("The number of allocated blocks is:%d\n",ptr->st_blocks);//文件分配块数量

     struct tm*accesstime,*lmodifytime,*lchangetime;//访问时间,修改时间,最后一个改变时间(属性)

     accesstime=localtime(&(ptr->st_atime));

     accesstime=localtime(&(ptr->st_mtime));

     accesstime=localtime(&(ptr->st_ctime));

     printf("The last access time is: %d::%d::%d\n",accesstime->hour,accesstime->min,accesstime->sec);

     printf("The last modify time is:%d::%d::%d\n",lmodifytime->hour,lmodifytime->min,lmodifytime->sec);

     printf("The last change time is:%d::%d::%d\n",lchangetime->hour,lchangetime->min,lchangetime->sec);

}

结构time_t可用用localtime转换成tm结构,获得本地时间。

原文地址:https://www.cnblogs.com/changefuture/p/2297716.html