系统调用的意义:
- 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 *) ; 9 void printpathto(ino_t) ; 10 void inum_to_name(ino_t , char * , int ) ; 11 12 int main() 13 { 14 printpathto(get_inode(".")); 15 putchar('\n'); 16 return 0 ; 17 } 18 19 void printpathto(ino_t this_inode) 20 { 21 ino_t my_inode ; 22 char its_name[BUFSIZ] ; 23 if(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 } 32 33 void inum_to_name(ino_t inode_to_find , char namebuf[] , int buflen) 34 { 35 DIR * dir_ptr ; 36 struct dirent * direntp ; 37 dir_ptr = opendir(".") ; 38 if(dir_ptr == NULL ) 39 { 40 perror("."); 41 exit(1); 42 } 43 while( (direntp = readdir(dir_ptr)) != NULL ) 44 { 45 if(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 mistake 49 closedir(dir_ptr) ; 50 return ; 51 } 52 } 53 fprintf(stderr, "%s\n", "Error looking for inode_num:" , inode_to_find ); 54 exit(1) ; 55 } 56 57 ino_t get_inode(char * fname) 58 { 59 struct stat info ; 60 if(stat(fname , &info ) != -1 ) 61 { 62 return info.st_ino ; 63 } 64 else 65 { 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版本是否是一样的安排。