chapter6:linux属性函数--stat, access, chmod, link, unlinkm,truncate

1 stat函数

1.1 函数描述

获取文件的属性

int stat(const char *pathname, struct stat *statbuf);

函数接收两个参数

  1. pathname: 传入文件的路径
  2. statbuf : 传出参数,是一个结构体,里面包含文件的各种属性

返回值

  1. 正确返回0
  2. 错误返回-1, 设置errno

这里stat结构体定义如下:

 struct stat {
   
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */
               mode_t    st_mode;        /* File type and mode */
               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;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               /* Since Linux 2.6, the kernel supports nanosecond
                  precision for the following timestamp fields.
                  For the details before Linux 2.6, see NOTES. */

               struct timespec st_atim;  /* Time of last access */
               struct timespec st_mtim;  /* Time of last modification */
               struct timespec st_ctim;  /* Time of last status change */

           #define st_atime st_atim.tv_sec      /* Backward compatibility */
           #define st_mtime st_mtim.tv_sec
           #define st_ctime st_ctim.tv_sec
           };

1.2 函数的使用

打印文件的属性
  0 #include <stdio.h> 
  1 #include <sys/types.h>
  2 #include <sys/stat.h>
  3 #include <unistd.h>
  4 #include <stdlib.h>
  5
  6 int main(int argc, char *argv[])
  7 {
   
  8     if(argc <2)                       //判断参数,需要传入一个文件名
  9     {
   
 10         printf("need arg.\n");
 11         exit(-1);
 12     }
 13
 14     struct stat statbuf;             //定义stat结构体
 15     stat(argv[1], &statbuf);         //调用stat函数,获取文件属性
 16     printf("st_mode: %o\n",statbuf.st_mode);   //打印文件属性
 17     printf("st_uid : %u\n",statbuf.st_uid);
 18     printf("st_gid : %u\n",statbuf.st_gid);
 19     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值