简体   繁体   English

搜索.exe的路径

[英]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. 因此,我正在寻找一段代码,使我可以搜索正在其中执行的文件的路径。例如,我正在做一个自动运行程序以用于Pendrive(示例),但是我不知道是否它最终将以D:,F:,G:或其他形式结束,因此程序将搜索其自己的路径,并根据使用“ if”语句找到的路径打开另一个文件。

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 GetModuleFileName此处的文档

EDITED - Pedro, the sample code from Microsoft handles a lot of things. 编辑-Pedro,Microsoft的示例代码处理了很多事情。 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. 在标准C ++中,argv [0]包含可执行文件的名称。 For a program invoked in the normal way this will be the path of the executable on Windows. 对于以常规方式调用的程序,这将是Windows上可执行文件的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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