获取exe可执行程序的命令行参数
在控制台中能够直接从参数中获取到命令行的参数,那么如果是应用程序,该如何从应用程序中获取命令行参数?
控制台可以使用下面的代码来获取命令行参数,参数下标从0开始,下标为0的参数是当前运行程序的路径,从下标1开始后面的参数是命令行中输入的参数
#include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; ++i) { printf("%d: %s\n", i, argv[i]); } return 0; }
输入参数为C:\Windows\System32>D:\code\TestGetCommandArgument\Debug\TestGetCommandArgument.exe i love you
输出结果如下图所示:
在应用程序中可以使用CommandLineToArgvW函数来获取命令行参数,注意在获取完参数时,需要调用LocalFree来释放内存,代码如下
#include <windows.h> #include <stdio.h> #include <shellapi.h> int main() { LPWSTR *szArglist; int nArgs; int i; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if( NULL == szArglist ) { wprintf(L"CommandLineToArgvW failed\n"); return 0; } else { for( i=0; i < nArgs; ++i) { printf("%d: %ws\n", i, szArglist[i]); } } // Free memory allocated for CommandLineToArgvW arguments. LocalFree(szArglist); return 0; }
输入参数为C:\Windows\System32>D:\code\TestGetCommandArgument\Debug\TestGetCommandArgument.exe i love you
运行结果跟上面代码结果一致。