views:

405

answers:

3

On Windows, you can go to "Run," type in "cmd," press enter, and start up "C:\Windows\system32\cmd.exe" rather easily. The same is true for "python" or "pythonw" (though nothing pops up in the second example). If all you know is that you want to execute "python" or "pythonw" and that it is on the PATH, what is the simplest way in C to figure out the fully qualified path name for the executable? This question seems to be highly related to the problem but does not give a final solution in C. _execp allows using the string "python" or "pythonw" but requires the qualified path for the first argument to the argv parameter of the function.

+3  A: 

Use getenv() to get the path, split it into strings (by semicolon on Windows), then test if there is an executable with the specified name in each directory in turn.

#include <iostream>
#include <sstream>
#include <sys/stat.h>

int main(void)
{
    std::stringstream path(getenv("PATH"));
    while (! path.eof())
    {
        std::string test;
        struct stat info;
        getline(path, test, ':');
        test.append("/myfile");
        if (stat(test.c_str(), &info) == 0)
        {
            std::cout << "Found " << test << std::endl;
        }
    }
}

Replace myfile with whatever, and on Windows replace ':' with ';' since the path separator is different.

Tom
...and the definition of "executable" is given by `echo %PATHEXT%`.
RichieHindle
+1  A: 

You can use PathFindOnPath(), and pass NULL for the second value to search the current PATH environment variable.

jeffamaphone
+2  A: 

Have a look at the shell APIs PathResolve (that, however, is marked as "removable in any future windows version", so I'd avoid it) and PathFindOnPath, that, instead, is a stable API. With PathFindOnPath, pass the filename to search (e.g. yourexecutable.exe) as the first parameter and NULL as the second one.

Matteo Italia