![](/img/trans.png)
[英]Visual Studio Addin - Get Name\Path of binary of a c++ project?
[英]Get Visual Studio project name (or exe file name ) to use it inside a C++ program
我需要在我的C ++程序中執行此命令:
WinExec("program_name.exe", SW_SHOW);
我正在使用Visual Studio 2010.有沒有辦法使用變量,常量或其他東西,以避免字符串“program_name.exe”? 現在它正在我的電腦上工作,但我的程序將在不同的計算機上進行測試,我不知道項目/ exe文件的名稱。
可執行文件名作為main函數中的參數傳遞:
int main(int argc, char **argv)
{
string exename = argv[0];
}
(詳細說明阿卜杜勒的答案:)
WinExec函數檢查您的錯誤,如下面的代碼所示。 如果您有興趣,可以在這里閱讀有關WinExec功能的更多信息。
我們來看看函數語法:
UINT WINAPI WinExec(
_In_ LPCSTR lpCmdLine,
_In_ UINT uCmdShow
);
由於LPCSTR
(長指向const字符串)實際上是一個const string
,你可以傳遞一個字符串類型作為它的第一個參數,但你需要將它轉換為一個const char *,它實際上是一個LPCSTR
(指向常量字符串的長指針) 。 在下面的代碼中,它使用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文件讀取應用程序名稱,測試app是否存在保存路徑,然后傳遞給該函數
這只是一個例子,同樣的想法
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.