• 20165334 实现mypwd


    学习pwd命令

    研究pwd实现需要的系统调用(man -k; grep),写出伪代码

    man -k pwd

    man -k current directory | grep 2

    man getcwd

    伪代码

    
    void get_file_name(*filepath){
      获取当前i-Node;
      通过i-Node获取当前路径名称filepath(%s);
    
       cd ..;
      获取当前i-Node;
      通过i-Node获取当前路径名filepath称(%s);
       get_file_name(*filepath);
      if(..i-Node == . i-Node){
      return;
      }
       printf('/'+filename);
      return;
    }
    

    实现mypwd

    编写mypwd

     #include <stdio.h>
     #include <sys/types.h>
     #include <sys/stat.h>
     #include <dirent.h>
     #include <pwd.h>
      ino_t get_inode(char *);
      void printpathto(ino_t);
      void inum_to_name(ino_t, char *, int);
    
      int main() {
     printpathto(get_inode(".")); /* print path to here */
     putchar('
    '); /* then add newline */
     return 0;
    }
    
    /*
     *        prints path leading down to an object with this inode
     * kind of recursive
    */
    void printpathto(ino_t this_inode) {
    ino_t my_inode;
    char its_name[BUFSIZ];
    if (get_inode("..") != this_inode) {
        chdir(".."); /* up one dir */
        inum_to_name(this_inode, its_name, BUFSIZ);/* get its name*/
        my_inode = get_inode("."); /* print head */
        printpathto(my_inode); /* recursively */
        printf("/%s", its_name); /* now print name of this */
      }
    }
    void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen) {
    DIR *dir; 
    struct dirent *direntp; 
    dir = opendir(".");
    
     while ((direntp = readdir(dir)) != NULL)
        if (direntp->d_ino == inode_to_find) {
            strncpy(namebuf, direntp->d_name, buflen);
            namebuf[buflen - 1] = ''; 
            closedir(dir);
            return;
        }
    
      exit(1);
    
    }
    
    
     ino_t get_inode(char *filename) {   //返回文件的i-Node值
    struct stat file;
    
    if (stat(filename, &info) == -1) {
        perror(fname);
        return 1;
    }
    return file.st_ino;
    }
    

    测试mypwd

  • 相关阅读:
    react组件之间传值方式
    html url 传递锚点并添加参数
    Spring Boot 构建WAR包
    Spring Boot Actuator 的使用
    Spring boot的启动加载原理
    intellij idea resin容器部署web工程
    Mybatis Mapper之见解
    踩坑----数据库阻塞
    redis缓存与数据库的记录不一致造成的问题.(乐观锁)
    H5中popstate事件的诡异行为
  • 原文地址:https://www.cnblogs.com/ltl123/p/10004369.html
Copyright © 2020-2023  润新知