stat查看文件属性

来源:互联网 发布:农村淘宝怎么开店 编辑:程序博客网 时间:2024/05/22 09:07
头文件:
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
查看文件属性函数有:
    int stat(const char *path,struct stat *buf);
    int fstat(int fd,struct stat *buf);
    int lstat(const char *path,struct stat *buf);

stat函数:
函数原型:int stat (const chat *path,struct stat *buf);
参数一:需要查看的文件路径
参数二:查看后的文件属性保存地址
返回值:成功返回0,失败返回-1

stat结构体如下:
     struct stat { 包含主次设备号   /dev/sda 
               dev_t     st_dev;   //dev_t ---》设备号类型,容纳该文件的那个设备的设备号。 普通文件所在的储存器设备号 major()主设备号
               ino_t     st_ino;  //inode number  ---》minor()次设备号
               mode_t    st_mode;   //---》文件权限(包含类型)
               nlink_t   st_nlink;   //---》Inode硬链接数●讲清硬链接与软连接的区别,即命令:ln -s为软连接,没有-s为硬链接
               uid_t     st_uid;     //---》文件属主(owner, 拥有者)的用户id
               gid_t     st_gid;      //---》文件属主(owner)的组id
               dev_t     st_rdev;     //---》文件的设备号(假如该文件是设备)       特殊文件设备号(驱动文件)
               off_t     st_size;   //文件内容的长度//st_size对普通文件(文本文件,二进制文件),文件内容的长度
                                   //st_size对目录而言,文件长度通常是一个数的倍数。●目录的内容是文件项数组  
                          //st_size对符号链接文件,符号链接文件的内容是它指向的文件的文件名●大小为指向文件名的字节
               blksize_t st_blksize; //block size---》块大小(与具体的硬件相关)
               blkcnt_t  st_blocks;  //---》文件占多少块(block,在linux下面每个block占512bytes)
               time_t    st_atime;  //access time ---》最后访问"文件内容"的时间, read/write
               time_t    st_mtime;  //modify  time ---》最后修改"文件内容"的时间,
               time_t    st_ctime;    //change time ---》最后改变"文件属性"的时间,●即改变i-node信息
           };

详细解释:
st_dev ---》普通文件所在的储存器设备号,即硬盘设备
st_redv---》驱动设备号
st_mode---》文件权限与文件类型获取
使用例子:
判断文件类型:if(S_ISREG(filemsg.st_mode));
获取文件权限:if(S_IFREG&filemsg.st_mode);

---------------------------------------------------------------------------------------
使用stat函数获取文件权限与文件大小
#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>int main(int argv,char **argc){if(argv<2){perror("stat fail no file:");}   struct stat filemsg;    stat(argc[1],&filemsg);if( S_IRUSR&filemsg.st_mode|| S_IWUSR && filemsg.st_mode){  printf("USR have read or write\n");//判断用户是否有读写程序} if(S_IRGRP&filemsg.st_mode|| S_IWGRP && filemsg.st_mode ){     printf("group have read or write\n");//判断用户组是否有读写程序}printf("the file size=%d\n",(int)filemsg.st_size);//打印文件大小}

--------------------------------------------------------------------------------------
测试文件权限函数access();
头文件:
    #include <unistd.h>
函数原型:
    int access(const char *pathname ,int mode);
参数一:要测试的文件路径
参数二:要测试的权限
                R_OK--->可读
                W_OK---》可写
                X_OK---》可执行
                F_OK---》文件是否存在
返回值:成功返回0,失败返回-1

获取文件路径函数
函数原型:
    char *getwd(char *buf);
功能:获取文件路径并存放到buf中
注意:该函数存在溢出的危险,因此应谨慎使用

获取环境变量的值:
头文件:
    #include <stdlib.h>
函数原型:
    char *getenv(const char *name);

删除文件函数
头文件:
    #include <stdio.h>
函数原型:
    int remove(const char *pathname);
参数一:要删除的文件路径名
返回值:成功返回0,失败返回-1