zoukankan      html  css  js  c++  java
  • Understanding Unix/Linux Programming-pwd指令练习

    系统调用的意义:

    1. mkdir:创建目录
    2. rmdir:删除空目录
    3. unlink:删除一个链接
    4. link:创建一个新链接
    5. rename:重命名或者删除一个链接
    6. 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('
    ');
    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 ] = '' ; // The book says : just in case of a mistake
    49             closedir(dir_ptr) ;
    50             return ;
    51         }
    52     }
    53     fprintf(stderr, "%s
    ", "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
    ", "Can not stat." );
    67         perror(fname) ;
    68         exit(1) ;
    69     }
    70 }

    其中使用到了递归操作,完成当前工作目录的输出。

      另外,在本人的OpenSuse Leap42.1上测试程序的时候,发现并不能显示到根目录,而是显示到了个人工作目录就停止了,后来通过“ls -ia”指令发现/home目录、根目录的“.” 以及根目录的“..”的inode号是一样的,都是2。所以并不能通过这种方法追溯的根目录,不过这不是关键就是了,这样的安排也应该和个人用户在自己的目录下工作有关系。不知道其他Linux版本是否是一样的安排。

  • 相关阅读:
    StarGAN v2
    STGAN
    Neo4j 图数据库查询
    StarGAN
    AttGAN
    分布式事务解决方案--Seata源码解析
    5分钟彻底了解Nginx的反向代理
    SpringBoot启动流程源码解析
    JAVA基础5--注解的实现原理
    Redis进阶三之底层存储数据结构及内存优化
  • 原文地址:https://www.cnblogs.com/NJdonghao/p/5263207.html
Copyright © 2011-2022 走看看