Understanding Unix/Linux Programming-pwd指令练习
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Understanding Unix/Linux Programming-pwd指令练习,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1870字,纯文字阅读大概需要3分钟。
内容图文
系统调用的意义:
- mkdir:创建目录
- rmdir:删除空目录
- unlink:删除一个链接
- link:创建一个新链接
- rename:重命名或者删除一个链接
- chdir:切换所调用进程的当前目录
1 #include <sys/types.h> 2 #include <sys/stat.h> 3 #include <unistd.h> 4 #include <stdio.h> 5 #include <dirent.h> 6 #include <stdlib.h> // Just in case of some calls 7 8 ino_t get_inode(char *) ; 9void printpathto(ino_t) ; 10void inum_to_name(ino_t , char * , int ) ; 1112int main() 13{ 14 printpathto(get_inode(".")); 15 putchar(‘\n‘); 16return0 ; 17} 1819void printpathto(ino_t this_inode) 20{ 21 ino_t my_inode ; 22char its_name[BUFSIZ] ; 23if(get_inode("..") != this_inode) 24 { 25 chdir("..") ; 26 inum_to_name(this_inode , its_name , BUFSIZ) ; 27 my_inode = get_inode("."); 28 printpathto( my_inode ) ; 29 printf("/%s", its_name ); 30 } 31} 3233void inum_to_name(ino_t inode_to_find , char namebuf[] , int buflen) 34{ 35 DIR * dir_ptr ; 36struct dirent * direntp ; 37 dir_ptr = opendir(".") ; 38if(dir_ptr == NULL ) 39 { 40 perror("."); 41 exit(1); 42 } 43while( (direntp = readdir(dir_ptr)) != NULL ) 44 { 45if(direntp -> d_ino == inode_to_find ) 46 { 47 strncpy(namebuf , direntp -> d_name , buflen ); 48 namebuf[buflen - 1 ] = ‘\0‘ ; // The book says : just in case of a mistake49 closedir(dir_ptr) ; 50return ; 51 } 52 } 53 fprintf(stderr, "%s\n", "Error looking for inode_num:" , inode_to_find ); 54 exit(1) ; 55} 5657 ino_t get_inode(char * fname) 58{ 59struct stat info ; 60if(stat(fname , &info ) != -1 ) 61 { 62return info.st_ino ; 63 } 64else65 { 66 fprintf(stderr, "%s\n", "Can not stat." ); 67 perror(fname) ; 68 exit(1) ; 69 } 70 }
其中使用到了递归操作,完成当前工作目录的输出。
另外,在本人的OpenSuse Leap42.1上测试程序的时候,发现并不能显示到根目录,而是显示到了个人工作目录就停止了,后来通过“ls -ia”指令发现/home目录、根目录的“.” 以及根目录的“..”的inode号是一样的,都是2。所以并不能通过这种方法追溯的根目录,不过这不是关键就是了,这样的安排也应该和个人用户在自己的目录下工作有关系。不知道其他Linux版本是否是一样的安排。
原文:http://www.cnblogs.com/NJdonghao/p/5263207.html
内容总结
以上是互联网集市为您收集整理的Understanding Unix/Linux Programming-pwd指令练习全部内容,希望文章能够帮你解决Understanding Unix/Linux Programming-pwd指令练习所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。