是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)
(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)
当前回答
下面的操作在macOS 10.15.7上运行得很好
brew install boost
main.cpp
#include <iostream>
#include <boost/filesystem.hpp>
int main(int argc, char* argv[]){
boost::filesystem::path p{argv[0]};
p = absolute(p).parent_path();
std::cout << p << std::endl;
return 0;
}
编译
g++ -Wall -std=c++11 -l boost_filesystem main.cpp
其他回答
也许连接当前工作目录与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
下面是获取执行应用程序的完整路径的代码:
变量声明:
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;
对于Win32, GetCurrentDirectory应该做到这一点。
只是迟来的堆砌在这里,…
没有标准的解决方案,因为这些语言不知道底层文件系统,所以正如其他人所说,基于目录的文件系统的概念超出了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.
对于相对路径,我是这样做的。我知道这个问题的年代久远,我只是想提供一个在大多数情况下都适用的更简单的答案:
假设你有一个这样的路径:
"path/to/file/folder"
出于某种原因,在eclipse中构建的linux可执行文件可以很好地使用它。然而,如果给窗口一个这样的路径来工作,它会变得非常混乱!
如上所述,有几种方法可以获得可执行文件的当前路径,但我发现在大多数情况下最简单的方法是将其附加到路径的FRONT:
"./path/to/file/folder"
只是补充”。/“应该让你整理好!”:)然后你可以从任何你想要的目录开始加载,只要它是可执行文件本身。
编辑:如果您试图从code::blocks启动可执行文件,这将不起作用,如果这是正在使用的开发环境,由于某些原因,code::blocks不能正确加载东西…: D
EDIT2:我发现的一些新情况是,如果您在代码中指定一个像这样的静态路径(假设示例。数据是你需要加载的东西):
"resources/Example.data"
如果你从实际目录中启动你的应用程序(或者在Windows中,你做一个快捷方式,并将工作目录设置为你的应用程序目录),那么它就会像这样工作。 在调试与缺少资源/文件路径相关的问题时,请记住这一点。(特别是在IDE中,当从IDE启动build exe时设置了错误的工作目录)