是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)

(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)


当前回答

你不能为此目的使用argv[0],通常它包含可执行文件的完整路径,但也不是必须的——进程可以在字段中使用任意值创建。

还要注意,当前目录和可执行文件所在的目录是两个不同的东西,所以getcwd()也帮不了你。

Windows上使用GetModuleFileName(), Linux上读取/dev/proc/procID/..文件。

其他回答

文件系统TS现在是一个标准(gcc 5.3+和clang 3.9+都支持),所以你可以使用它的current_path()函数:

std::string path = std::experimental::filesystem::current_path();

在gcc(5.3+)包含文件系统,你需要使用:

#include <experimental/filesystem>

用-lstdc++fs标记链接你的代码。

如果你想在Microsoft Visual Studio中使用文件系统,请阅读本文。

你不能为此目的使用argv[0],通常它包含可执行文件的完整路径,但也不是必须的——进程可以在字段中使用任意值创建。

还要注意,当前目录和可执行文件所在的目录是两个不同的东西,所以getcwd()也帮不了你。

Windows上使用GetModuleFileName(), Linux上读取/dev/proc/procID/..文件。

在POSIX平台上,可以使用getcwd()。

在Windows上,您可以使用_getcwd(),因为使用getcwd()已被弃用。

对于标准库,如果Boost对您来说足够标准,那么我会建议Boost::filesystem,但是他们似乎已经从建议中删除了路径规范化。您可能必须等到TR2可以随时获得完全标准的解决方案。

在Windows上,最简单的方法是使用stdlib.h中的_get_pgmptr函数来获取一个指向字符串的指针,该字符串表示可执行文件的绝对路径,包括可执行文件的名称。

char* path;
_get_pgmptr(&path);
printf(path); // Example output: C:/Projects/Hello/World.exe

只是迟来的堆砌在这里,…

没有标准的解决方案,因为这些语言不知道底层文件系统,所以正如其他人所说,基于目录的文件系统的概念超出了c / c++语言的范围。

on top of that, you want not the current working directory, but the directory the program is running in, which must take into account how the program got to where it is - ie was it spawned as a new process via a fork, etc. To get the directory a program is running in, as the solutions have demonstrated, requires that you get that information from the process control structures of the operating system in question, which is the only authority on this question. Thus, by definition, its an OS specific solution.