windows 如何在C程序中获取当前文件夹的父目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5233559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:22:00  来源:igfitidea点击:

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

cwindowsdos

提问by Priyanka

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?

我正在尝试获取我有程序的当前文件夹的父目录。我需要包含在我拥有的 C 程序中。我尝试通过字符串方法来解决它,但我觉得可以有更好更简单的方法。例如:如果他的路径是“C:\Application\Config”,那么我想得到 - “C:\Application” 只是父路径。
有人可以帮我解决这个问题吗?

Thanks, Priyanka

谢谢,普里扬卡

回答by RichieHindle

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 = '##代码##';
}

回答by Benoit

Sometimes just adding \..will suffice if you are not afraid by MAX_PATH.

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

回答by Chris Browne

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.

如果你想在跳转到新目录之前对它执行一些字符串函数,你的问题会立即变得更难解决。我要做的方式反映了 RichieHindle 的解决方案 - 将当前目录从完整路径中剥离,然后你就剩下父目录的路径,你可以用它来处理你心中的内容。

回答by Lundin

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

在 Windows 操作系统中,您需要的 API 函数称为 GetCurrentDirectory()。

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

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