C编程:如何获取目录名?

时间:2014-06-05 15:46:37

标签: c directory posix stat dirent.h

我正在编写一个代码,用于使用递归函数打印从根目录到当前目录或引用目录的路径。但我无法获取目录名称,只能得到.. 基础案例和调用之间出现问题  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;
}

在输入命令行

时应该是正确的结果
./pathto .

应该打印出从根目录到我当前目录的路径

或命令行如此

./pathto file.txt

应打印出从根目录到file.txt的路径

1 个答案:

答案 0 :(得分:2)

使用<dirent.h>stat执行此操作是可能的,但非常棘手。 POSIX为这个名为realpath的函数提供了一个函数。省略错误检查:

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

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