2017-2018-1 20155336 《信息安全系统设计基础》加分作业:实现mypwd

什么是PWD?

  • 用man pwd查看:

  • 用于打印当前工作目录的工作路径
  • 1.命令格式:pwd[选项]
  • 2.命令功能:查看”当前工作目录“的完整路径
  • 3.常用参数: 一般情况下不带任何参数。如果目录是链接时,格式:pwd -P 显示出实际路径,而非使用连接(link)路径。

实现mypwd

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
ino_t get_inode(char*);
void pwd(ino_t);
void name(ino_t,char*,int);

int main()
{
    pwd(get_inode("."));  
    printf("\n");
    return 0;
}

void pwd(ino_t this_inode)
{
    ino_t my_inode;
    char its_name[BUFSIZ];
    if (get_inode("..")!=this_inode)                                 
    {
        chdir(".."); 
        name(this_inode,its_name,BUFSIZ);
        my_inode = get_inode(".");
        pwd(my_inode);
        printf("/%s",its_name);
    }
}

void name(ino_t inode,char* namebuf,int buflen)   //找到i-节点对应的文件名
{
    DIR* cdir;
    struct dirent* direntp;
    cdir = opendir(".");
    while((direntp = readdir(cdir)) != NULL)
    {
        if(direntp->d_ino == inode)
        {
            strncpy(namebuf,direntp->d_name,buflen);
            namebuf[buflen-1] = '\0';
            closedir(cdir);
            return;
        }
    }
    printf("error looking for inode\n");
}

ino_t get_inode(char* fname)            //根据文件名,返回-i节点
{
    struct stat info;
    stat( fname, &info);
    return info.st_ino;
}

测试mypwd

posted on 2017-12-06 23:04  丿尛丶熊  阅读(132)  评论(0编辑  收藏  举报