LuckyLast
LuckyLast

Reputation: 61

C programming: How to get directory name?

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

Upvotes: 1

Views: 8353

Answers (1)

Fred Foo
Fred Foo

Reputation: 363547

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;
}

Upvotes: 2

Related Questions