APUE(第四章)文件和目录

本文详细介绍了文件系统中的stat、fstat、lstat和fstatat函数,用于获取文件信息。这些函数返回文件的设备号、inode、模式、权限、所有者、组、大小、最后访问、修改和状态改变时间等。同时,文章讲解了文件类型,如普通文件、目录、特殊文件等,以及文件权限的设置和测试。此外,还涵盖了文件所有权的变更、文件长度、空洞、文件截断、链接、重命名、符号链接以及文件时间戳的修改。内容涉及文件系统的基本概念和操作,对理解Linux文件系统管理至关重要。

重点理解文件系统

函数stat、fstat、fstatat和lstat

#include <sys/stat.h>
int stat(const char *restrict pathname,struct stat *restrict buf);
int fstat(int fd,struct stat *buf);
int lstat(const char *restrict pathname,struct stat *restrict buf);
int fstatat(int fd,const char *restrict pathname,struct stat *restrict buf,int flag);//成功返回0;出错返回-1;
  • 以上是返回文件有关的信息结构

  • buf是传入传出参数,用来存放文件信息

  • stat函数返回与此命名文件有关的信息结构

  • fstat函数获得已在文件描述符fd上打开文件的有关信息

  • lstat类似于stat,当文件是一个符号链接时,lstat返回该符号连接的有关信息,而不是由该符号连接引用的文件的信息

  • fstatat

    • 为一个相对于当前打开目录(由fd参数指向)的路径名返回统计信息
    • flag控制是否跟随一个符号链接
      • AT_SYMLINK_NOFOLLOW标志被设置,fstatat返回符号链接本身信息否则默认为符号链接指向实际文件的信息
    • fd参数为AT_FDCWD,pathname参数是一个相对路径名,fstatat会计算相对于当前目录的pathname,如果pathname为绝对路径,fd则忽略,和stat一样
  • ubuntu 20.04 stat结构如下

struct stat
  {
   
   
    __dev_t st_dev;		/* Device.  */
#ifndef __x86_64__
    unsigned short int __pad1;
#endif
#if defined __x86_64__ || !defined __USE_FILE_OFFSET64
    __ino_t st_ino;		/* File serial number.	*/
#else
    __ino_t __st_ino;			/* 32bit file serial number.	*/
#endif
#ifndef __x86_64__
    __mode_t st_mode;			/* File mode.  */
    __nlink_t st_nlink;			/* Link count.  */
#else
    __nlink_t st_nlink;		/* Link count.  */
    __mode_t st_mode;		/* File mode.  */
#endif
    __uid_t st_uid;		/* User ID of the file's owner.	*/
    __gid_t st_gid;		/* Group ID of the file's group.*/
#ifdef __x86_64__
    int __pad0;
#endif
    __dev_t st_rdev;		/* Device number, if device.  */
#ifndef __x86_64__
    unsigned short int __pad2;
#endif
#if defined __x86_64__ || !defined __USE_FILE_OFFSET64
    __off_t st_size;			/* Size of file, in bytes.  */
#else
    __off64_t st_size;			/* Size of file, in bytes.  */
#endif
    __blksize_t st_blksize;	/* Optimal block size for I/O.  */
#if defined __x86_64__  || !defined __USE_FILE_OFFSET64
    __blkcnt_t st_blocks;		/* Number 512-byte blocks allocated. */
#else
    __blkcnt64_t st_blocks;		/* Number 512-byte blocks allocated. */
#endif
#ifdef __USE_XOPEN2K8
    /* Nanosecond resolution timestamps are stored in a format
       equivalent to 'struct timespec'.  This is the type used
       whenever possible but the Unix namespace rules do not allow the
       identifier 'timespec' to appear in the <sys/stat.h> header.
       Therefore we have to handle the use of this header in strictly
       standard-compliant sources special.  */
    struct timespec st_atim
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值