简体   繁体   中英

Search for path of .exe

So I'm looking for a piece of code that allows me to search for the path of the file it's being executed in. For example, I'm doing an autorun program for use in pendrives (example) but I don't know if it'll end up as D:, F:, G: or whatever so the program would search it's own path and open another file based on the path he is found using some 'if' statements.

Here's what I thought:

    #include <stdlib.h>
    #include <iostream>
    using namespace std;

    int main () {
    // Insert 'search path' code and needed variables here.

    if (-ThePath- == "d:\\AutoRun.exe")
        {
         system ("d:\\MyFolder\\OtherProgram.exe");
        }
    else if (-ThePath- == "f:\\AutoRun.exe")
        {
         system ("f:\\MyFolder\\OtherProgram.exe");
        }
    else if (-ThePath- == "g:\\AutoRun.exe")
        {
         system ("g:\\MyFolder\\OtherProgram.exe");
        }
    else
        {
         cout << "An error ocurred.\n";
         cout << "Press enter to exit...\n";
         cin.get();
        };
    return 0;
    }

Is there some way this could be done?

GetModuleFileName : documentation here

EDITED - Pedro, the sample code from Microsoft handles a lot of things. To get the file path, all you need is :

TCHAR szPath[MAX_PATH];

if( !GetModuleFileName( NULL, szPath, MAX_PATH ) ) {

    // handle error in GetModuleFileName

} else {

    // now, szPath contains file path

};

In standard C++ argv[0] contains the name of the executable. For a program invoked in the normal way this will be the path of the executable on Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM