2017-2018-1 20155338 加分项目——PWD的实现

2017-2018-1 20155338 加分项目——PWD的实现

项目要求

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

实现过程

首先通过man 命令了解了一下pwd的用法

试试pwd命令的用法:

代码实现:

需要用到readdir函数

可以用man 命令了解了一下readdir函数的用法。

代码如下:


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include<string.h>
ino_t get_inode(char* file);
void get_inode_name(ino_t i_node,char *file_name,int length);
void print_direct(ino_t i_node);
void main()
{
    ino_t i_node;
   
    print_direct(get_inode("."));
   printf("
");


}

void print_direct(ino_t i_node)
{
    ino_t n_inode;
    char *file_name[256];
 if(get_inode("..")!=get_inode(".")){
      chdir("..");
      get_inode_name(i_node,file_name,256);
     n_inode=get_inode(".");
     print_direct(n_inode);
     printf("/%s",file_name);
}
}

void get_inode_name(ino_t i_node,char *file_name,int length)
{
      DIR* dir_ptr;
    struct dirent* direntp;
        dir_ptr = opendir(".");
    while((direntp = readdir(dir_ptr)) != NULL)
    {
          if(direntp->d_ino==i_node)
        {
            strncpy(file_name,direntp->d_name,length);
            file_name[length-1]='';
             closedir(dir_ptr);
    }

       }

}


ino_t get_inode(char* file)
{
struct stat buf;
if(stat(file,&buf)!=-1)
{
   return buf.st_ino;
}
else{
   printf("failed to get inode");
 }
}

运行结果为:

原文地址:https://www.cnblogs.com/Hdywan/p/7861395.html