stat, fstat, and lstat Functions
本部分讨论的内容主要围绕3个stat函数及其返回值。
#include <sys/stat.h> int stat(const char *restrict pathname, struct stat *restrict buf); int fstat(int filedes, struct stat *buf); int lstat(const char *restrict pathname, struct stat *restrict buf); |
stat函数返回pathname的stat结构体。
fstat返回fd代表的文件的stat结构体。
lstat与stat很相似,但是当pathname是一个软链接时,lstat返回的是软链接的信息,而不是软链接指向的文件。
File Types
文件类型
regular file, directory file, block special file, character special file, FIFO(pipe), socket, symbolic link.
根据stat结构体中的st_mode判断文件类型
- S_ISREG():regular file
- S_ISDIR():directory file
- S_ISCHR():character special file
- S_ISBLK():block special file
- S_ISFIFO():pipe or FIFO
- S_ISLNK():symbolic link
- S_ISSOCK():socket
- S_TYPEISMQ():message queue
- S_TYPEISSEM():semaphore
- S_TYPEISSHM():shared memory object
access函数
测试当前用户拥有的文件权限
#include <unistd.h> int access(const char *pathname, int mode); |
mode取值:man 2 access查看帮助文档
umask函数
设置文件被创建时的权限
#include <sys/stat.h> mode_t umask(mode_t cmask); |
cmask取值:man 2 umask查看帮助文档
chmod/fchmod函数
更改文件的权限
#include <sys/stat.h> int chmod(const char *pathname, mode_t mode); int fchmod(int filedes, mode_t mode); |
mode取值:man 2 chmod查看帮助文档
chown/fchown/lchown函数
更改文件的uid&gid
#include int chown(const char *pathname, uid_t owner, gid_t group); int fchown(int filedes, uid_t owner, gid_t group); int lchown(const char *pathname, uid_t owner, gid_t group); |