是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像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.
其他回答
下面的操作在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
只是我的两美分,但下面的代码在c++ 17中不能移植吗?
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
}
至少在Linux上对我有用。
根据前面的想法,我现在有:
std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");
与实现:
fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
{
static auto exe_parent_path = fs::path(exe_path).parent_path();
return exe_parent_path / filename;
}
main()中的初始化技巧:
(void) prepend_exe_path("", argv[0]);
感谢@Sam Redway的argv[0]想法。当然,我知道当OP提出这个问题时,c++ 17还没有出现很多年。
如果你想要一种没有库的标准方式:不。标准中没有包含目录的整个概念。
如果您同意对接近标准库的某些(可移植的)依赖是可以的:使用Boost的文件系统库并请求initial_path()。
恕我直言,这是你能得到的最接近的结果,并且有良好的因果报应(Boost是一套完善的高质量库)
对于控制台的Windows系统,可以使用system(dir)命令。控制台提供目录等信息。在cmd下阅读有关dir命令的信息。但是对于类unix系统,我不知道…如果执行了该命令,请读取bash命令。Ls不显示目录…
例子:
int main()
{
system("dir");
system("pause"); //this wait for Enter-key-press;
return 0;
}
在POSIX平台上,可以使用getcwd()。
在Windows上,您可以使用_getcwd(),因为使用getcwd()已被弃用。
对于标准库,如果Boost对您来说足够标准,那么我会建议Boost::filesystem,但是他们似乎已经从建议中删除了路径规范化。您可能必须等到TR2可以随时获得完全标准的解决方案。