zoukankan      html  css  js  c++  java
  • Mypwd实现

    Mypwd实现

    实现要求

    1. 学习pwd命令
    2. 研究pwd实现需要的系统调用(man -k; grep),写出伪代码
    3. 实现mypwd
    4. 测试mypwd

    学习pwd命令

    image

    可知pwd是用来显示当前/活动目录名称

    命令格式:pwd [选项]

    pwd –P:显示当前目录的物理路径

    pwd -L:显示当前目录的连接路径

    一般情况下不带任何参数

    伪代码

    获取当前i-Node
    从根目录中找到和i-Node相同的值
    用i-Node向前递归
    输出路径
    

    实现mypwd

    #include<stdio.h>  
    #include<sys/stat.h>  
    #include<dirent.h>  
    #include<stdlib.h>  
    #include<string.h>  
    #include<sys/types.h>  
    
    void printpath();  
    char *inode_to_name(int);  
    int getinode(char *);  
    int main()  
    {  
    printpath();  
    putchar('
    ');  
    return ;  
    }  
    void printpath()  
    {  
    int inode,up_inode;  
    char *str;  
    inode = getinode(".");  
    up_inode = getinode("..");  
    chdir("..");  
    str = inode_to_name(inode);  
    if(inode == up_inode) {    
        return;  
    }  
    printpath();  
    printf("/%s",str);  
    }  
    int getinode(char *str)  
    {  
    struct stat st;  
    if(stat(str,&st) == -1){  
        perror(str);  
        exit(-1);  
    }  
    return st.st_ino;  
    }  
    char *inode_to_name(int inode)  
    {  
    char *str;  
    DIR *dirp;  
    struct dirent *dirt;  
    if((dirp = opendir(".")) == NULL){  
        perror(".");  
        exit(-1);  
    }  
    while((dirt = readdir(dirp)) != NULL)  
    {  
        if(dirt->d_ino == inode){  
            str = (char *)malloc(strlen(dirt->d_name)*sizeof(char));  
            strcpy(str,dirt->d_name);  
            return str;  
        }  
    }  
    perror(".");  
    exit(-1);  
    }
    

    测试mypwd

    image

  • 相关阅读:
    第四章5
    第四章4
    第四章3
    第四章2
    第四章1
    第四章例4-8
    第四章例4-7
    第四章例4-6
    第四章例4-5
    第四章例4-4
  • 原文地址:https://www.cnblogs.com/KY-high/p/10003606.html
Copyright © 2011-2022 走看看