1

I'm writing a code for printing out the path from root to current directory or referred directory, using recursive function. but I can't get the directory name, only get .. Problem happened among base case and call dirent->name.

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>

static void list_dir (const char * dir_name)
{
    DIR * d;
    struct dirent *e;
    struct stat sb;
    struct stat sb2;
    long childIno;
    long parentIno;
    char parent[200];

    stat(dir_name, &sb);
    if (stat(dir_name, &sb) == -1) {
        perror("stat");
        exit(EXIT_FAILURE);
    }

    childIno = (long) sb.st_ino;

    /* get parent dir name */

    snprintf(parent, sizeof(parent), "%s/..", dir_name);
    d = opendir(parent);


    stat(parent, &sb2);
    if (stat(parent, &sb2) == -1) {
        perror("stat2");
        printf("parent name: \n");
        exit(EXIT_FAILURE);
    }
    parentIno = (long) sb2.st_ino;


    if (d == NULL) {
        printf("Cannot open dircetory '%s'\n", parent);
    }

    /*below code is really messed up*/
    if (childIno == parentIno) {
        while ((e = readdir(d)) != NULL) {
            printf("base case %s\n", e->d_name);
        break;
         }

    }else{
        list_dir(parent);

    }

    /*code above here is really messed up*/

    /* After going through all the entries, close the directory. */
    closedir (d);
}

int main (int argc, char** argv)
{
    list_dir (argv[1]);
    return 0;
}

right result should be when typing command line

./pathto .

should print out path from root directory to my current directory

or if command line as this

./pathto file.txt

should print out path from root directory to file.txt

2
  • are you looking for realpath()?
    – Pavel
    Commented Jun 5, 2014 at 15:51
  • @Pavel. No sorry, I have to use stat and dirent
    – LuckyLast
    Commented Jun 5, 2014 at 16:17

1 Answer 1

2

Doing this using <dirent.h> and stat is possible, but really tricky. POSIX offers a function for this called realpath. Omitting error checking:

#include <limits.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char buf[PATH_MAX];
    puts(realpath(argv[1], buf));
    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.