文件系统(ext2)
- super block 描述整个分区的文件系统信息,例如块大小、文件系统版本号
- GDT 块组描述符表
- Block Bitmap 块位图 显示哪个block可用
- inode Bitmap inode Bitmap
- inode表 存储文件的属性信息。如:权限、类型 叫作文件属性
dentry
目录项,其本质依然是结构体,重要成员变量有两个 {文件名,inode,…},而文件内容(data)保存在磁盘盘块中。
stat函数
- 作用 将文件属性通过传出参数返回调用者
- 参数1 文件名 参数2 iinode结构体指针
- 返回值 成返回0;失败返回-1
truct stat buf; //设置参数
stat("temp.txt", &buf); //函数调用
printf("st_mode = %x\n", buf.st_mode); //输出文件属性
printf("st_ino = %ld\n", buf.st_ino);/输出文件inode
lstat
与stat相相同 ,避免穿透链接
eg:stat->stat.soft 链接文件 stat 执行stat.soft时 会显示是目录 因为显示得是链接文件的属性
if(S_ISREG(buf.st_mode))//判断是不是文件
p = "regular file";
else if(S_ISDIR(buf.st_mode))//判断目录
p = "directory";
access
测试指定文件是否存在/拥有某种权限。
成功/具备该权限:0;失败/不具备 -1
if ((ret = access("abc", W_OK)) < 0) {
printf("error ret = %d\n", ret);}
目录权限
opendir/closedir
- 根据传入的目录名打开一个目录(表示目录整体) (库函数)
- DIR *opendir(const char *name);
- DIR * 类似于 FILE *(第一节中文件描述符指针 指向对应的文件结构体)
readdir
- 读取目录
- struct dirent *readdir(DIR *dirp);
- 成功返回==目录项(表示每个文件)==结构体指针
- ino_t d_ino; inode编号
- char d_name[256];文件名
递归遍历目录
void isfile(char *name) //处理目录/文件
{
struct stat sbuf;
stat(name, &sbuf) ;
if (S_ISDIR(sbuf.st_mode) { //判定是否为目录
fetchdir(name, isfile); //回调函数
}
printf("%8ld %s\n", sbuf.st_size, name); //不是目录,则是普通文件,直接打印
}
void fetchdir(const char *dir, void (*fcn)(char *))//该函数被调用,既已被判定为目录
{
struct dirent *sdp; //,目录项结构体
DIR *dp; //目录结构体
dp = opendir(dir)) ;
while ((sdp = readdir(dp)) != NULL) {
if (strcmp(sdp->d_name, ".") == 0 || strcmp(sdp->d_name, "..") == 0) { //防止出现无限递归
//结构体属性 用 ->因为 用"." 优先于结构体*
continue;
}
sprintf(name, "%s/%s", dir, sdp->d_name); //将dir和d_name格式化连接在一起 格式化到name
(*fcn)(name); //回调函数
}
closedir(dp);
}
dup/dup2
- 重定向
- nt dup(int oldfd); 成功:返回一个新文件描述符;失败:-1
- int dup2(int oldfd, int newfd);
int fd, fd2;
char *str = "use fd write in\n";
char *str2 = "use ====fd2==== write\n";
fd = open("test", O_WRONLY|O_TRUNC|O_CREAT, 0644); //3
fd2 = open("test", O_WRONLY); //4
dup2(fd, fd2); fd2指向test
close(fd);
write(fd2, str2, strlen(str2)); //还可以向test中写