获取Visual Studio项目名(或exe文件名)以在C++程序中使用它

Get Visual Studio project name (or exe file name ) to use it inside a C++ program

本文关键字:程序 C++ 以在 文件名 项目 Studio Visual exe 获取      更新时间:2023-10-16

我需要在我的C++程序中执行这个命令:

WinExec("program_name.exe", SW_SHOW);

我正在使用Visual Studio 2010。有没有什么方法可以使用变量、常量或其他东西来避免字符串"program_name.exe"?现在它在我的计算机上运行,但我的程序将在另一台计算机上测试,我不知道项目.exe文件的名称。

可执行文件名称作为参数传递到主函数中:

int main(int argc, char **argv)
{
    string exename = argv[0];
}

(详细说明abdul的答案:)

WinExec函数为您检查错误,您可以在下面的代码中看到。如果您感兴趣,可以在此处阅读有关WinExec功能的更多信息。

让我们来看看函数语法:

UINT WINAPI WinExec(
  _In_  LPCSTR lpCmdLine,
  _In_  UINT uCmdShow
);

由于LPCSTR(指向Const字符串的长指针)实际上是const string,因此可以将字符串类型作为其第一个参数进行传递,但需要将其转换为Const char*,这实际上是一个LPCSTR(指向Const字符串的长指针)。在下面的代码中,它是通过使用c_str()来完成的。

#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int main()
{
   string appName="yourappname.exe";
   int ExecOutput = WinExec(appName.c_str(), SW_SHOW);
    /* 
    If the function succeeds, the return value is greater than 31.
    If the function fails, the return value is one of the following error values.
    0 The system is out of memory or resources.
    ERROR_BAD_FORMAT The .exe file is invalid.
    ERROR_FILE_NOT_FOUND The specified file was not found.
    ERROR_PATH_NOT_FOUND The specified path was not found.
    */
    if(ExecOutput > 31){
        cout << appName << " executed successfully!" << endl;
    }else {
        switch(ExecOutput){
        case 0:
            cout << "Error: The system is out of memory or resources." << endl;
            break;
        case ERROR_BAD_FORMAT:
            cout << "Error: The .exe file is invalid." << endl;
            break;
        case ERROR_FILE_NOT_FOUND:
            cout << "Error: The specified file was not found." << endl;
            break;
        case ERROR_PATH_NOT_FOUND:
            cout << "Error: The specified path was not found." << endl;
            break;
        }
    }
   return 0;
}

我特意排除了(abdul创建的)另一个函数,以避免被您的问题所迷惑,并让您更清楚地了解WinExec函数的实际用途。你可以很容易地添加他创建的应用程序检查功能,并在其中放入你需要的任何其他检查

您可以将要运行的.exe文件存储在与运行它的.exe文件相同的位置,这样您就可以保持硬编码的常量名称。

或者,一个很好的方法是通过命令行参数传入要运行的程序名称,下面是解析参数的教程:教程

这样,您就可以用变量替换该字符串,并在运行.exe.

时通过命令行传入名称

打开conf文件读取应用程序名称,测试应用程序是否存在保存路径,然后传递到函数

这只是一个例子,相同的想法

int main()
{
   string appName;
   if (getAppName(appName)) 
   {
      WinExec(appName.c_str(), SW_SHOW);
     /// WinExec(appName, SW_SHOW);
     /// ^^^ one of these
   }
   return 0;
}

函数看起来像这个

bool getAppName(string& appName)
{
   string str;
   ///file open, and read;
   ///read(str)
   if(fileExist(str))
   {
       appName = str;
       return true;
   }
   return false;
}