Boost.Filesystem how to find out in which directory your executable is?
So开发者_开发问答 I run my app. I need for it to know where its executable is. How to find path to it using Boost.Filesystem?
boost::filesystem::system_complete(argv[0]);
e.g.
[davka@bagvapp Debug]$ ./boostfstest
/home/davka/workspaces/v1.1-POC/boostfstest/Debug/boostfstest
Note that this gives you the full path including the executable file name.
You cannot, Boost.Filesystem does not provide such functionality.
But starting with Boost 1.61 you can use Boost.Dll and function boost::dll::program_location
:
#include <boost/dll.hpp>
boost::dll::program_location().parent_path();
You can't do it reliably with boost::filesystem.
However if you're on windows you can call GetModuleFileName
to get the complete path of the executable and then use boost::filesystem
to get the directory. ( see parent_path)
As discussed more comprehensively here, the most reliable way to do that is not through boost::filesystem. Instead, your implementation should take into the consideration the operating system on which the application is running.
However, for a quick implementation without portability concerns, you can check if your argv[0] returns the complete path to executable. If positive, you can do something like:
namespace fs=boost::filesystem;
fs::path selfpath=argv[0];
selfpath=selfpath.remove_filename();
From C++ 14 you don't need Boost, you can use the filesystem of the standard library you can do that easily: (I can confirm this works on Windows and Linux as well)
#include <iostream>
#include <filesystem>
namespace fs = std::experimental::filesystem;
int main()
{
fs::path p = argv[0]; // or "C:executable_name.exe";
std::cout << "Current path is " << fs::current_path() << '\n'
<< "Absolute path for " << p << " is " << fs::absolute(p) << '\n'
<< "System complete path for " << p << " is " << fs::system_complete(p) << '\n';
}
Sample copied from the documentation: https://en.cppreference.com/w/cpp/experimental/fs/absolute
If you mean from inside the executable that you're running, you can use boost::filesystem::current_path()
精彩评论