是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
当前回答
只是迟来的堆砌在这里,…
没有标准的解决方案,因为这些语言不知道底层文件系统,所以正如其他人所说,基于目录的文件系统的概念超出了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.
其他回答
对于Win32, GetCurrentDirectory应该做到这一点。
也许连接当前工作目录与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
对于控制台的Windows系统,可以使用system(dir)命令。控制台提供目录等信息。在cmd下阅读有关dir命令的信息。但是对于类unix系统,我不知道…如果执行了该命令,请读取bash命令。Ls不显示目录…
例子:
int main()
{
system("dir");
system("pause"); //this wait for Enter-key-press;
return 0;
}
正如Minok提到的,在C标准或c++标准中没有指定这样的功能。例如,这被认为纯粹是特定于操作系统的特性,并且在POSIX标准中指定。
Thorsten79给出了很好的建议,它是Boost。文件系统库。然而,如果你不想让你的程序有任何二进制形式的链接时间依赖关系,这可能是不方便的。
我推荐的一个很好的替代方案是100%只包含标题的STLSoft c++库Matthew Wilson (c++必读书籍的作者)。PlatformSTL提供了对系统特定API的访问:Windows上的WinSTL和Unix上的UnixSTL,因此它是可移植的解决方案。所有特定于系统的元素都是使用特征和策略指定的,因此它是可扩展的框架。当然,还提供了文件系统库。
下面是获取执行应用程序的完整路径的代码:
变量声明:
char pBuf[256];
size_t len = sizeof(pBuf);
窗口:
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;
Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;