学习pwd命令
![](https://img2018.cnblogs.com/blog/1289294/201811/1289294-20181122220420138-28409309.png)
研究pwd实现需要的系统调用(man -k; grep),写出伪代码
man -k pwd
![](https://img2018.cnblogs.com/blog/1289294/201811/1289294-20181122220614587-1559096222.png)
man -k current directory | grep 2
![](https://img2018.cnblogs.com/blog/1289294/201811/1289294-20181122220716652-773075720.png)
man getcwd
![](https://img2018.cnblogs.com/blog/1289294/201811/1289294-20181122221050773-464711604.png)
![](https://img2018.cnblogs.com/blog/1289294/201811/1289294-20181122221314917-1608402250.png)
伪代码
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('\n'); /* 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] = '\0';
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
![](https://img2018.cnblogs.com/blog/1289294/201811/1289294-20181122221856651-1464222338.png)