文件系统
文件储存
inode
其本质为结构体,存储文件的属性信息。如:权限、类型、大小、时间、用户、盘块位置……也叫作文件属性管理结构,大多数的 inode 都存储在磁盘上。
少量常用、近期使用的 inode 会被缓存到内存中。
dentry
目录项,其本质依然是结构体,重要成员变量有两个 {文件名,inode,…},而文件内容(data)保存在磁盘盘块中。
stat函数
函数作用:获取文件属性(从 inode 结构体中获取)
函数原型:
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
参数:
参数 1:文件名
参数 2:inode 结构体指针 (传出参数)
返回值:
成功返回 0;
失败返回-1
设置 errno 为恰当值。
区别 :stat会穿透符号链接;lstat:不会
link和Unlink隐式回收
函数作用:
link 函数,可以为已经存在的文件创建目录项(硬链接)。
unlink 函数,删除一个文件的目录项dentry,使硬链接数-1;
int link(const char *oldpath, const char *newpath);
int unlink(const char *pathname);
**unlink 函数的特征:**清除文件时,如果文件的硬链接数到 0 了,没有 dentry 对应,但该文件仍不会马上被释放。要等到所有打开该文件的进程关闭该文件,系统才会挑时间将该文件释放掉。
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int fd, ret;
char *p = "test of unlink\n";
char *p2 = "after write something.\n";
fd = open("temp.txt", O_RDWR|O_CREAT|O_TRUNC, 0644);
if(fd < 0){
perror("open temp error");
exit(1);
}
ret = write(fd, p, strlen(p));
if (ret == -1) {
perror("-----write error");
}
printf("hi! I'm printf\n");
ret = write(fd, p2, strlen(p2));
if (ret == -1) {
perror("-----write error");
}
printf("Enter anykey continue\n");
getchar();
ret = unlink("temp.txt"); //具备了被释放的条件
if(ret < 0){
perror("unlink error");
exit(1);
}
close(fd);
return 0;
}
递归遍历目录
- 判断命令行参数,获取用户要查询的目录名。 int argc, char *argv[1]
argc == 1 --> ./ - 判断用户指定的是否是目录。 stat S_ISDIR(); --> 封装函数 isFile() { }
- 读目录:
read_dir() {
opendir(dir)
while (readdir()){
普通文件,直接打印
目录:
拼接目录访问绝对路径。sprintf(path, “%s/%s”, dir, d_name)
递归调用自己。–> opendir(path) readdir closedir
}
closedir()
}
read_dir() --> isFile() —> read_dir()