一、函数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:重命名