linux 文件属性

在 shell 下直接使用 ls 就可获得文件的属性
在程序中,用 stat/ fstat/ lstat 函数,获取文件的属性
函数可通过命令:man 2 stat 查看

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

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

函数的返回值都是 0,当有错误发生时返回 -1,错误代码存放在 error 中。
区别:
①stat:用于获取由参数 file_name 制定的文件名的状态信息,保存在参数 struct stat *buf 中。
②fstat:与 stat 的区别在于该函数由文件描述符来获取文件的参数,文件的参数依旧保存在 buf 中。
③lstat:与 stat 的区别在与如果对于链接文件,lstat 返回的是链接文件本身的状态信息,stat 返回的是链接文件所指向的文件的状态信息。
struct stat *buf 保存的文件状态信息的:

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
           };

st_dev:文件的设备编号
st_ino:文件的 i-node(i 节点编号)
st_mode:文件的类型和存储权限
st_nlink:连接到该文件的硬链接数目,刚建立的文件值为1
st_uid:文件所有者的 id
st_gid:文件所有组的 id
st_rdev:若此文件为设备文件,则其为设备编号
st_size:文件大小,以字节计算,对连接文件,改大小是其所只想的文件名的长度
st_blksize:文件系统的 I/O 缓冲大小
st_blocks:占用文件区块的个数

对于 st_mode 包含的文件类型信息,POSIX 标准定义了一系列宏。
S_ISLINK(st_mode):判断是否为符号链接
S_ISREG(st_mode):一般文件
S_ISDIR(st_mode):目录文件
S_ISCHR(st_mode):设备文件
S_ISBLK(st_mode):块设备文件
S_ISFIFO(st_mode):先进先出文件
S_ISSTOCK(st_mode):判断是否是 socket

常用的有:st_mode, st_uid, st_gid, st_size, st_atime, st_mtime。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值