struct stat结构的应用

2014/10/1416:29:54 发表评论

我们知道Linux中有一个命令叫stat,它可以看到文件的各种属性,下面是文件package.xml的属性:

# stat package.xml 
  File: "package.xml"
  Size: 31782           Blocks: 64         IO Block: 4096   普通文件
Device: fd00h/64768d    Inode: 2243435     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/ UNKNOWN)   Gid: ( 1000/ UNKNOWN)
Access: 2014-06-17 16:40:45.432619616 +0800
Modify: 2011-05-15 06:14:56.000000000 +0800
Change: 2014-06-17 16:40:45.433679323 +0800

stat用来判断没有打开的文件,而fstat用来判断打开的文件.我们使用最多的属性是st_mode.通过着属性我们可以判断给定的文件是一个普通文件还是一个目录,连接等等.可以使用下面几个宏来判断.
S_ISLNK(st_mode):是否是一个连接.

S_ISREG是否是一个常规文件.

S_ISDIR是否是一个目录

S_ISCHR是否是一个字符设备.

S_ISBLK是否是一个块设备

S_ISFIFO是否是一个FIFO文件.

S_ISSOCK是否是一个SOCKET文件. 

下面我们来仔细看一下struct stat结构的内容:

//! 需要包含de头文件

#include <sys/types.h>

#include <sys/stat.h> 

int stat(const char *filename, struct stat *buf); //! prototype,原型 

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*/

    gid_t       st_gid;     /* group ID of owner - group 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 - */

};

我们来写一个具体的实例来验证一下:

#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
int main (int argc ,char *argv[])
{
        struct stat buf;
        int result;

        if(argc < 2 )
        {
                printf("%s [filename]\n",argv[0]);
                return -1;
        }
        result = stat (argv[1], &buf);
        if (result != 0)
        {
                perror ("Failed ^_^");
        }
        else
        {
                //! 文件的大小,字节为单位
                printf("size of the file in bytes: %u\n" , buf.st_size );
                //! 文件创建的时间
                printf("time of creation of the file: %s\n" , ctime (&buf.st_ctime) );
                //! 最近一次修改的时间
                printf("time of last modification of the file: %s\n" ,ctime (&buf.st_mtime) );
                //! 最近一次访问的时间
                printf("time of last access of the file: %s\n", ctime (&buf.st_atime) );
        }
        return 0;
}

 编译运行结果如下:

# ./stat stat.c     
size of the file in bytes: 754
time of creation of the file: Tue Oct 14 16:28:39 2014

time of last modification of the file: Tue Oct 14 16:28:39 2014

time of last access of the file: Tue Oct 14 16:28:41 2014
  • 微信扫码赞助
  • weinxin
  • 支付宝赞助
  • weinxin

发表评论

您必须才能发表评论!