操作系统真象还原[14章/十四]-获得文件属性

        获得文件属性通过sys_stat函数来实现,本篇也只有这一个函数,这个函数的形式如下:

int32_t sys_stat(const char* path, struct stat* buf)

        该函数会通过search_file函数搜索路径为path的文件或目录存不存在,存在的话则将文件或目录的大小信息、文件或目录的inode_no、文件或目录的文件类型存入到结构为stat的buf中,比较简单就不多说了,直接上代码(fs/fs.c以及fs/fs.h中)

struct stat {
    uint32_t st_ino;                //inode编号
    uint32_t st_size;               //尺寸
    enum file_types st_filetype;    //文件类型
};
/* 在buf中填充文件结构相关信息,成功时返回0,失败返回-1 */
int32_t sys_stat(const char* path, struct stat* buf) {
    /* 判断是否是根目录 */
    if(!strcmp(path, "/") || !strcmp(path, "/.") || !strcmp(path, "/..")) {
        buf->st_filetype = FT_DIRECTORY;
        buf->st_ino = 0;
        buf->st_size = root_dir.inode->i_size;
        return 0;
    }

    /* 检查path路径下的文件或目录是否存在 */
    struct path_search_record searched_record;
    memset(&searched_record, 0, sizeof(struct path_search_record));
    int32_t ret = -1;
    int32_t inode_no = search_file(path, &searched_record);
    if(inode_no == -1) {
       printk("sys_stat: %s not found!\n", searched_record.searched_path);
    } else {
        uint32_t searched_path_depth = path_depth_cnt(searched_record.searched_path);
        uint32_t path_depth = path_depth_cnt(path);
        if(searched_path_depth == path_depth) {
            /* 存在返回stat中的相关信息 */
            struct inode* obj_inode = inode_open(cur_part, inode_no);
            buf->st_size = obj_inode->i_size;
            buf->st_ino = inode_no;
            buf->st_filetype = searched_record.file_type;
            inode_close(obj_inode);
            ret = 0;
        } else {
            printk("sys_stat: %s is regular file!\n", searched_record.searched_path);
        }
    }
    return ret;
}

       实验结果

#include "print.h"
#include "init.h"
#include "debug.h"
#include "memory.h"
#include "thread.h"
#include "interrupt.h"
#include "console.h"
#include "process.h"
#include "syscall.h"
#include "syscall-init.h"
#include "stdio.h"
#include "fs.h"
#include "dir.h"

int main(void)
{
    put_str("I am kernel\n");
    init_all();
    intr_enable();

    struct stat obj_stat;
    sys_stat("/", &obj_stat);
    printf("/'s info\n  i_no:%d\n   size:%d\n   filetype:%s\n", obj_stat.st_ino, obj_stat.st_size, obj_stat.st_filetype == 2 ? "directory" : "regular");
    sys_stat("/dir1", &obj_stat);
    printf("/dir1's info\n  i_no:%d\n   size:%d\n   filetype:%s\n", obj_stat.st_ino, obj_stat.st_size, obj_stat.st_filetype == 2 ? "directory" : "regular");

    while(1);
    return 0;
}

         这里根目录存在file1和dir1两个目录项所以大小是96,而dir1下的subdir1目录已经删除了只有'.'和'..'两个目录项所以大小是48。到此,本章终于结束了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值