3.1.2 stat、fstat、lstat

包含的头文件:

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

 

1.stat

/**************************
 *功能:通过一个文件名,获取文件的属性
 *path:文件名
 *buf:结构体struct stat类型的文件属性
 *返回值:成功返回0,失败返回-1并设置errno
 * **********************/
int stat(const char *path , struct stat *buf);

 

2.fstat

/*************************
 *功能:通过一个文件描述符,获取文件的属性
 *fd:文件描述符
 *buf:结构体struct stat类型的文件属性
 *返回值:成功返回0,失败返回-1并设置errno
 * ***********************/
int fstat(int fd , struct stat *buf);

3.lstat

/*****************************
 *功能:通过一个链接文件名字,获取文件的属性(单单是链接文件的属性)
 *path:链接文件路径
 *buf:结构体struct stat类型的文件属性
 *返回值:成功返回0,失败返回-1并设置errno
 * **************************/
int lstat(const char *path , struct stat *buf);

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 */
           };
[root@localhost myls]# ls -l -i -a -n
总用量 20
538685   drwxr-xr-x.     2          0        0      4096   3月  13 18:32 .
inod号      权限       硬链接数      uid     gid      size       修改时间
st_dev:包含这个文件的设备ID号
st_ino:inode号
st_nlink:硬链接号
st_mode:权限存放的位置

/********************
 * 功能:获取文件大小
 * *****************/
#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) { off_t f_size ; if(argc < 2 ) { fprintf(stderr , "Usage...\n"); exit(1); } f_size = flen(argv[1]); printf("file%s size = %ld\n",argv[1],f_size); exit(0); }

 





 
posted @ 2016-03-14 13:31  muzihuan  阅读(266)  评论(0编辑  收藏  举报