简体   繁体   中英

C Programming: How can I get parent directory?

In my pathto.c I want to open parent directory

static void list_dir (const char * dir_name)
{
    DIR * d;
    struct dirent *e;

    d = opendir ("dir_name/..");


    if (d == NULL) {
        printf("Cannot open dircetory");
    }
}

but I got "Cannot open directory"

How can I call opendir to open parent directory?

Thank you.

You will probably need to append /.. to the value of list_dir before calling opendir() . For example, you could do it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM