分享

使用stat函数,获取文件属性

 lchjczw 2013-01-23

#include<sys/types.h>

#include<sys/stat.h>

#include<unistd.h>

intstat(const char*path,structstat *buf);

intfstat(intfd,structstat *buf);

intlstat(const char*path,structstat *buf);


这三个函数的区别是:

stat用于获取有参数file_name指定的文件名的状态信息,保存在参数structstat *buf中。fstat于stat的区别在于fstat是通过文件描述符来指定文件,也就是通过open函数所返回获得的fd。lstat与stat 的区别在于,对于符号链接文件,lstat返回的是符号链接文件本身的状态信息,而stat返回的是符号链接指向的文件状态信息。

参数 structstat *buf是一个保存文件状态信息的结构体

 文件对应的属性
   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<stdio.h>

#include<time.h>

#include<sys/stat.h>

#include<unistd.h>

#include<sys/types.h>

#include<errno.h>

intmain(intargc,char*argv[])

{

   structstat buf;

   //检查参数

   if(argc != 2) {

        printf("Usage: my_stat <filename>\n");

        exit(0);

    }

   //获取文件属性

   if( stat(argv[1], &buf) == -1 ) {

        perror("stat:");

        exit(1);

    }

   //打印出文件属性

    printf("device is: %d\n", buf.st_dev);

    printf("inode is: %d\n", buf.st_ino);

    printf("mode is: %o\n", buf.st_mode);

    printf("number of hard links  is: %d\n", buf.st_nlink);

    printf("user ID of owner is: %d\n", buf.st_uid);

    printf("group ID of owner is: %d\n", buf.st_gid);

    printf("device type (if inode device) is: %d\n", buf.st_rdev);

    printf("total size, in bytes is: %d\n", buf.st_size);

    printf(" blocksize for filesystem I/O is: %d\n", buf.st_blksize);

    printf("number of blocks allocated is: %d\n", buf.st_blocks);

    printf("time of last access is: %s", ctime(&buf.st_atime));

    printf("time of last modification is: %s", ctime(&buf.st_mtime));

    printf("time of last change is: %s", ctime(&buf.st_ctime));

   return0;

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多