Shatur95
Shatur95

Reputation: 113

How to get the absolute file path from the system PATH in C++?

Is it possible to get the full path to the file by its name if it is in the system PATH?

For example, I have cmake in my PATH. Can I get the full path to it using C++ filesystem library? I just want to make cross-platform check for file existence.

Upvotes: 0

Views: 735

Answers (1)

drescherjm
drescherjm

Reputation: 10857

Boost.Process has this functionality in search_path . Here is a small linux example testing search path to find the location of the sh executable in the system path.

#include <iostream>
#include <cstdlib>
#include <boost/process/search_path.hpp>
#include <string>

int main()
{ 
    auto myPath = boost::process::search_path("sh");

    std::cout << "sh executable path " << myPath << std::endl;

}

Live Environment to test: https://wandbox.org/permlink/c3TbKq4sliBjxRVc

Output:

Start
sh path "/bin/sh"
0
Finish

Upvotes: 1

Related Questions