20165232 实现mypwd
题目要求
- 学习pwd命令
- 研究pwd实现需要的系统调用(man -k; grep),写出伪代码
- 实现mypwd
- 测试mypwd
学习pwd命令
- 用man pwd 查看帮助文档
- 显示当前目录所在路径 pwd
- 显示当前目录的物理路径 pwd –P
- 显示当前目录的连接路径:pwd -L
2.研究pwd实现需要的系统调用(man -k; grep),写出伪代码
man-k directory | grep 2
{ getinode(".");获取当前目录节点 getinode(".."); 获取父目录节点 记录当前节点的目录名; 只有当inode == up_inode时,打印。}
3.实现pwd命令
代码
#include#include #include #include #include #include void printpath(); char *inode_to_name(int); int getinode(char *); int main() { printpath(); putchar('\n'); return ; } void printpath() { int inode,up_inode; char *str; inode = getinode("."); up_inode = getinode(".."); chdir(".."); str = inode_to_name(inode); if(inode == up_inode) { // printf("/%s",str); 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); }