简体   繁体   中英

How to get the parent directory of the current folder in a C program?

I am trying to get the parent directory of the current folder in which i have the program. I need to include in the C program I have. I tried doing it through string methods and solve it, but I feel there can be a better and simpler way. Eg: If his path is “C:\\Application\\Config”, then I want to get - “C:\\Application” the just parent path.
Can some one please help me with this?

Thanks, Priyanka

To in-place truncate a string at its last backslash:

char pathname[MAX_PATH];
GetCurrentDirectory(MAX_PATH, pathname);
char* last_backslash = strrchr(pathname, '\\'); 
if (last_backslash)
{
    *last_backslash = '\0';
}

如果你不害怕MAX_PATH有时只需添加\\..就足够了。

It's difficult to answer your question since you haven't really specified what you want to -do- with the path once you have it. If you want to change to the new directory, that's easy, you just use whatever function you'd normally use to change directory but pass it ".." instead of a full path - that's because on all sane filesystems, ".." is a 'magic' directory which exists inside all other directories and refers to the parent thereof.

If you want to perform some string function on the new directory before jumping to it, your problem instantly becomes a lot more difficult to solve. The way I'd go about doing it mirrors RichieHindle's solution - strip the current directory away from the full path then you're left with the parent directory's path with which you can muck about to your heart's content.

In Windows OS, the API function you need is called GetCurrentDirectory().

http://msdn.microsoft.com/en-us/library/aa364934%28v=vs.85%29.aspx

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