这两篇文章是有共同点的。
stat fstat lstat
这三个函数的作用是类似的。区别只是在参数上的不同。
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(....)
fstat 是传递的文件描述符,lstat是符号链接。这几个函数统一都返回stat结构体,这个结构体的 内容如下:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
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; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
尤其注意 st_mode位
access faccessat
#include <unistd.h>
int access(const char *pathname, int mode);
int faccessat(ing fd, const char *pathname, int mode, int flag);
access - check real user’’s permissions for a file
确定文件和目录的访问权限。
参数1是文件或者文件夹的路径。
参数2是要判断的模式,可能值是一个或者多个R_OK、W_OK、X_OK和F_OK(文件是否存在)的组合体。
在
#define R_OK 4 /* Test for read permission */
#define W_OK 2 /* Test for write permission */
#define X_OK 1 /* Test for execute permission */
返回说明,成功为0,失败返回-1,errno被设定为以下的某个值。参考
EINVAL: 模式值无效
EACCES: 文件或路径名中包含的目录不可访问
ELOOP : 解释路径名过程中存在太多的符号连接
ENAMETOOLONG:路径名太长
ENOENT: 路径名中的目录不存在或是无效的符号连接
ENOTDIR: 路径名中当作目录的组件并非目录
EROFS: 文件系统只读
EFAULT: 路径名指向可访问的空间外
EIO: 输入输出错误
ENOMEM: 不能获取足够的内核内存
ETXTBSY:对程序写入出错
相关的代码放在了github上。
chmod, fchmod,fchmodat
这里主要是利用 “或”的关系将那几个模式选中或者删除。
file Truncatioh
#include <unistd.h>
int truncate(const char *pathname, off_t length);
int ftruncate(int fd, off_t length);
这两个函数截取length长得bytes在相应的文件中。
许可位与特殊属性位
1.建立文件的模式
fd = creat(“newfile”, 0744);
指定新创建文件的许可位为
rwxr–r–;
这个参数只是请求,而不是命令, 内核会通过”新建文件掩码”来得到文件的最终模式 ,啥是”新建文件掩码”呢,简单地说,就是,比如说,你要一个文件不能被同组用户和 其他用户修改,那么,你的原意就是将文件的许可位关掉:
—-w–w-
这样即可达到目的。
我们使用
umask(022);
实现了同样的目的。
2.改变文件的模式
程序可以通过系统调用chmod来改变文件的模式。
chmod ("/tmp/myfile", 04764);
chmod ("/tmp/myfile", S_ISUID | S_IRWXU | S_IRGRP | S_IRGRP | S_IROTH)
3.文件所有者与组
文件所有者就是创建文件的用户,用户通过creat 建立文件时,内核把文件所有者设为 运行程序的用户,如果程序具有set-user-ID位,那么新文件所有者就是程序的文件所 有者。
修改文件所有者和组
chown(“file1”, 200,40);
file systems
每一个i-node有一个连接计数,只有当link count为0的时候,这个i-node才可以被删除。这个信息是stat中的st_nlink表示。每一个i-node指向了n个data block,这里面存放就是文件的数据。