是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
当前回答
如果你想要一种没有库的标准方式:不。标准中没有包含目录的整个概念。
如果您同意对接近标准库的某些(可移植的)依赖是可以的:使用Boost的文件系统库并请求initial_path()。
恕我直言,这是你能得到的最接近的结果,并且有良好的因果报应(Boost是一套完善的高质量库)
其他回答
这个问题是15年前问的,所以现在现有的答案是不正确的。如果你使用的是c++ 17或更高版本,现在的解决方案非常简单:
#include <filesystem>
std::cout << std::filesystem::current_path();
更多信息请参见cppreference.com。
只是迟来的堆砌在这里,…
没有标准的解决方案,因为这些语言不知道底层文件系统,所以正如其他人所说,基于目录的文件系统的概念超出了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.
当前.exe的路径
#include <Windows.h>
std::wstring getexepathW()
{
wchar_t result[MAX_PATH];
return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));
}
std::wcout << getexepathW() << std::endl;
// -------- OR --------
std::string getexepathA()
{
char result[MAX_PATH];
return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));
}
std::cout << getexepathA() << std::endl;
也许连接当前工作目录与argv[0]?我不确定这是否适用于Windows,但它适用于linux。
例如:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv) {
char the_path[256];
getcwd(the_path, 255);
strcat(the_path, "/");
strcat(the_path, argv[0]);
printf("%s\n", the_path);
return 0;
}
运行时输出:
jeremy@jeremy-desktop: ~ /桌面。美元/测试 /home/jeremy/Desktop/./test
Boost Filesystem的initial_path()的行为类似于POSIX的getcwd(),它们本身都不能满足您的需要,但是将argv[0]附加到它们中的任何一个都可以做到这一点。
您可能会注意到,结果并不总是很漂亮——您可能会得到/foo/bar/../ baz/a这样的东西。Out或/foo/bar//baz/a。out,但我相信它总是会产生一个有效的路径,该路径命名可执行文件(注意,路径中连续的斜杠被折叠为一个)。
我以前用envp (main()的第三个参数)写了一个解决方案,它在Linux上有效,但在Windows上似乎行不通,所以我基本上是在推荐和其他人以前一样的解决方案,但附加了为什么它实际上是正确的,即使结果并不漂亮。