跟我一起写操作系统

    返回首页    发表留言
本文作者:李德强
          第五节 rm命令
 
 

        rm命令为remove files or directories的简写,它与mkdir相反,功能为删除文件/文件夹。同样,rm命令也只能在可写入的文件/目录上执行。实现如下:

session = malloc(sizeof(s_session));
session->current_path = malloc(SHELL_CMD_LEN);
int params[2];
params[0] = 7;
params[1] = (int) session;
__asm__ volatile("int $0x80" :: "a"(params));
u8 flag = 0x0;
char *path = malloc(0x200);
for (int i = 1; i < argc; i++)
{
        if (args[i][0] == '-')
        {
                for (int j = 1; j < str_len(args[i]); j++)
                {
                        if (args[i][j] == 'r')
                        {
                                //递归删除,通指删除文件夹
                                flag |= (0x1 << 0);
                        }
                        else if (args[i][j] == 'f')
                        {
                                //强制删除,通指只读文件或文件夹
                                flag |= (0x1 << 1);
                        }
                }
        }
        else
        {
                str_copy(args[i], path);
        }
}
if (str_len(path) > 0)
{
        char *full_path = malloc(SHELL_CMD_LEN);
        full_path[0] = '\0';
        if (path[0] == '/')
        {
                repath(path, NULL, full_path);
        }
        //不是以'/'开头: 相对路径
        else
        {
                repath(path, session->current_path, full_path);
        }
        FILE *fp = fopen(full_path, FS_MODE_READ);
        if (fp != NULL)
        {
                fclose(fp);
                del_file(full_path);
                return 0;
        }
        fclose(fp);
        int len = str_len(full_path);
        if (full_path[len - 1] != '/')
        {
                full_path[len] = '/';
                full_path[len + 1] = '\0';
        }
        s_fs *fs_work = malloc(sizeof(s_fs));
        u32 dev_id = 0;
        int status = fs_find_path_by_user(full_path, session->uid, session->gid, &dev_id, fs_work);
        if (status == FS_STATUS_NO_FILE_DIR)
        {
                printf("-bash: \"%s\": no such file or directory.\n", path);
        }
        else if (status == FS_STATUS_NO_PERMISSION)
        {
                printf("-bash: \"%s\": permission denied.\n", path);
        }
        else
        {
                if ((flag >> 0) & 0x1 == 1)
                {
                        del_dir(full_path);
                }
                else
                {
                        printf("rm: cannot remove \"%s\": is a directory.\n", path);
                }
        }
        free(fs_work);
        free(full_path);
}
free(path);
free(session->current_path);
free(session);

        运行结果:



 

        源代码的下载地址为:

https            https://github.com/magicworldos/lidqos.git 
git              git@github.com:magicworldos/lidqos.git 
subverion        https://github.com/magicworldos/lidqos 
branch           v0.30

 

    返回首页    返回顶部
  看不清?点击刷新

 

  Copyright © 2015-2023 问渠网 辽ICP备15013245号