码迷,mamicode.com
首页 > 其他好文 > 详细

2017-2018-1 20155230 mypwd实现

时间:2017-11-19 22:21:09      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:open   blog   read   amp   根目录   dir   perror   types.h   std   

mypwd实现

  • 实现步骤:

    1.找到本目录的i-节点 
    2.进入父目录,找到i-节点对应的文件名 
    3.循环以上过程,直到到达根目录
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <dirent.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‘);
    return 0;
    }
    void printpathto(ino_t this_inode)
    {
    ino_t my_inode;
    char its_name[BUFSIZ];
    /*如果本目录的i-节点与上级目录不同,即本目录不是根目录*/
    if (get_inode("..")!=this_inode)                                 
    {
        chdir("..");         //进入上级目录
        inum_to_name(this_inode,its_name,BUFSIZ);
        my_inode = get_inode(".");
        printpathto(my_inode);
        printf("/%s",its_name);
    }
    }
    void inum_to_name(ino_t inode_to_find,char* namebuf,int buflen)   //找到i-节点对应的文件名,并放在字符数组里
    {
    DIR* dir_ptr;
    struct dirent* direntp;
    dir_ptr = opendir(".");
    if (dir_ptr == NULL)
    {
        perror(".");
        exit(1);
    }
    /*下面这块每太搞明白,功能是寻找制定i-节点的目录,将目录名复制到namebuf中。
    但是没明 白他是怎么寻找的*/
    /*明白了,每次循环direntp都会指向下一个文件,详见testreaddir.c。
    但这是怎么做到的呢?*/
    while((direntp = readdir(dir_ptr)) != NULL)
    {
        if(direntp->d_ino == inode_to_find)
        {
            strncpy(namebuf,direntp->d_name,buflen);
            namebuf[buflen-1] = ‘\0‘;
            closedir( dir_ptr);
            return;
        }
    }
    fprintf( stderr , "error looking for inum % d\n" ,inode_to_find);
    exit (1) ;
    }
    ino_t get_inode(char* fname)            //根据文件名,返回-i节点
    {
    struct stat info;
    if ( stat( fname, &info) == -1){
        fprintf( stderr , "Cannot stat ");
        perror(fname);
        exit (1);
    }
    return info.st_ino;
    }

2017-2018-1 20155230 mypwd实现

标签:open   blog   read   amp   根目录   dir   perror   types.h   std   

原文地址:http://www.cnblogs.com/J1n233/p/7862145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!