Linux命令pwd的自我实现

简介: Linux命令pwd的自我实现

参考资料

man手册
Unix-Linux编程实践教程

pwd概述

命令pwd用来显示到达当前目录的路径。例如:
在这里插入图片描述

pwd的工作原理

在每个目录文件下都会有".“和” . . “两个目录,”.“指的是当前目录,”. .“指的是上一级目录。
我们可以通过”.“获得当前目录的inode-id,然后再进入该目录的上一级目录,通过刚刚获得的inode-id去匹配当前目录中文件的inode-id从而找到刚刚目录的目录名。
然后不断重复上面操作,当”.“和”. ."的inode-id相同时就可以认为已经到达了文件树的顶端

所要用到的函数

在这里插入图片描述

分析(运行的步骤逻辑)

(1).得到".“的inode-id(使用stat)
(2) .使用chdir返回上一级目录
(3).判断是否到达文件数的顶端(判断” . “和” . . "的inode-id是否相同,若到达程序执行完成,若没有继续下面步骤)
(4).找到inode-id连接的文件名字
(5).重复上面步骤,直到到达树的顶端.

代码实现

#include
#include
#include
#include
#include
#include
#include
ino_t get_inode(char*);
void printpathto(ino_t);
void inum_to_name(ino_t,char*,int );
int main()
{
    
 printpathto(get_inode("."));
 putchar('\n');
 return 0;
}
void printpathto(ino_t this_inode)
{
    
 ino_t my_inode;
 char its_name[BUFSIZ];
 if(get_inode("..")!=this_inode)
 {
    
   chdir("..");
   inum_to_name(this_inode,its_name,BUFSIZ);
   my_inode = get_inode(".");
   printpathto(my_inode);
   printf("/%s",its_name);
 }
}
void inum_to_name(ino_t inode_to_find,char *namebuf,int buflen)
{
    
 DIR *dir_ptr;
 struct dirent*direntp;
 dir_ptr=opendir(".");
 if(dir_ptr==NULL)
 {
    
   perror(".");
   exit(1);
 }
 while((direntp =readdir(dir_ptr))!=NULL)
   if(direntp->d_ino==inode_to_find)
   {
    
     strncpy(namebuf,direntp->d_name,buflen);
     namebuf[buflen-1]='\0';
     closedir(dir_ptr);
     return;
   }
 fprintf(stderr,"error looking for inum %d\n",inode_to_find);
 exit(1);
}
ino_t get_inode(char *fname)
{
    
 struct stat info;
 if(stat(fname,&info)==-1)
 {
    
   fprintf(stderr,"Cannot stat");
   perror(fname);
   exit(1);
 }
 return info.st_ino;
}

效果展示

在这里插入图片描述

相关文章
|
22天前
|
Linux 网络安全 Python
linux后台运行命令screen的使用
linux后台运行命令screen的使用
56 2
linux后台运行命令screen的使用
|
22天前
|
Ubuntu Linux
查看Linux系统架构的命令,查看linux系统是哪种架构:AMD、ARM、x86、x86_64、pcc 或 查看Ubuntu的版本号
查看Linux系统架构的命令,查看linux系统是哪种架构:AMD、ARM、x86、x86_64、pcc 或 查看Ubuntu的版本号
144 3
|
18天前
|
机器学习/深度学习 安全 网络协议
Linux防火墙iptables命令管理入门
本文介绍了关于Linux防火墙iptables命令管理入门的教程,涵盖了iptables的基本概念、语法格式、常用参数、基础查询操作以及链和规则管理等内容。
178 73
|
11天前
|
Linux Shell
Linux 中 Tail 命令的 9 个实用示例
Linux 中 Tail 命令的 9 个实用示例
40 6
Linux 中 Tail 命令的 9 个实用示例
|
7天前
|
设计模式 Java Linux
Linux的20个常用命令
Linux的23个常用命令
Linux的20个常用命令
|
16天前
|
Linux 应用服务中间件 nginx
|
3天前
|
机器学习/深度学习 存储 Linux
linux中强大且常用命令:find、xargs、grep
linux中强大且常用命令:find、xargs、grep
25 9
|
3天前
|
SQL 移动开发 Linux
linux下find、grep命令详解
linux下find、grep命令详解
37 8
|
9天前
|
存储 Linux 编译器
linux中vim介绍以及常用命令大全
linux中vim介绍以及常用命令大全
32 8
|
12天前
|
机器学习/深度学习 安全 网络协议
Web安全-Linux网络命令
Web安全-Linux网络命令
14 1