第四章-文件和目录

这篇博客介绍了Linux系统中用于获取文件信息的stat、fstat、lstat和fstatat函数,以及它们的使用方式和返回信息结构。此外,还涵盖了文件类型如普通文件、目录、特殊文件等,并提供了判断文件类型的宏。同时,提到了文件访问权限的相关概念。
摘要由CSDN通过智能技术生成

一、函数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 ltat(const char* restrict pathname, struct stat* restrict buf);
int fstatat(int fd, const char* restrict pathname, struct stat* restrict buf, int flag);

成功返回0;失败返回-1.
一旦给出pathname, stat函数将返回此命名文件的信息结构。fstat函数获得已在描述符fd上打开文件的有关信息。lstat类似于stat,但当命名文件时一个符号链接(软链接)时,返回该符号链接的有关信息,而不是引用的文件。
fstatat(略)

buf参数指向一个我们提供的结构体,其基本形式为:

struct stat{
	mode_t		st_mode; //file type & mode(permissons)
	ino_t		st_ino;  //i-node number
	nlink_t		st_nlink; //number of links;
	uid_t     	st_uid;
	gid_t     	st_gid;
	off_t     	st_size;  //size in bytes
	struct timespec st_atime; //time of last access
 	struct timespec st_mtime; //time of last modification
 	struct timespec st_ctime; //time of last file status change
};

对于timespec, 至少包括以下两个字段(s和ns):

time_t tv_sec;
long tv_nsec;

二、文件类型

(1)普通文件(regular file):包含文本或二进制数据的文件。
(2)目录文件(directory file)
(3)块特殊文件(block special file):提供对设备 带缓冲的访问
(4)字符特殊文件(character special file):提供对设备 不带缓冲的访问
(5)FIFO:用于进程间通信,也叫命名管道(named pipe)
(6)套接字(socket):用于进程间通信
(7)符号链接(symbolic link):软链接
文件类型信息包含在stat结构体中的st_mode成员中:

  • S_ISREG() 普通文件
  • S_ISDIR() 目录文件
  • S_ISCHR() 字符特殊文件
  • S_ISBLK() 块特殊文件
  • S_ISFIFO() 管道或FIFO
  • S_ISLINK() 符号链接
  • S_ISSOCK()套接字

三、文件访问权限

在这里插入图片描述
关于文件、目录的访问权限可以参考另一篇博客:
https://blog.csdn.net/sunximei/article/details/120593683

四、函数umask;chmod;chown;mkdir等等

umask:为进程设置文件模式,通常在creat创建文件时

#include <sys/stat.h>
mode_t umask(mode_t cmask);

chmod,fchmod,fchmodat: 更改现有文件的访问权限

#include <sys/stat.h>
int chmod(const char* pathname, mode_t mode);
int fchmod(int fd, mode_t mode);
int fchmodat(int fd, const char* pathname, mode_t mode, int flag);

chown,fchown,fchownat和lchown: 更改文件的用户ID和组ID

link,linkat,unlink,unlinkat和remove:

rename和renameat:重命名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值