在Windows程序中,将从GetCommandLine获取的命令行解析为多个参数的规范方法是什么,类似于Unix中的argv数组?似乎CommandLineToArgvW为Unicode命令行执行此操作,但我找不到非Unicode等效项.我应该使用Unicode吗?如果没有,我该如何解析命令行?
这是CommandLineToArgvA的一个实现,它将工作委托给CommandLineToArgvW,MultiByteToWideChar和WideCharToMultiByte.
LPSTR* CommandLineToArgvA(LPSTR lpCmdLine, INT *pNumArgs) { int retval; retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, NULL, 0); if (!SUCCEEDED(retval)) return NULL; LPWSTR lpWideCharStr = (LPWSTR)malloc(retval * sizeof(WCHAR)); if (lpWideCharStr == NULL) return NULL; retval = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, lpCmdLine, -1, lpWideCharStr, retval); if (!SUCCEEDED(retval)) { free(lpWideCharStr); return NULL; } int numArgs; LPWSTR* args; args = CommandLineToArgvW(lpWideCharStr, &numArgs); free(lpWideCharStr); if (args == NULL) return NULL; int storage = numArgs * sizeof(LPSTR); for (int i = 0; i < numArgs; ++ i) { BOOL lpUsedDefaultChar = FALSE; retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, NULL, 0, NULL, &lpUsedDefaultChar); if (!SUCCEEDED(retval)) { LocalFree(args); return NULL; } storage += retval; } LPSTR* result = (LPSTR*)LocalAlloc(LMEM_FIXED, storage); if (result == NULL) { LocalFree(args); return NULL; } int bufLen = storage - numArgs * sizeof(LPSTR); LPSTR buffer = ((LPSTR)result) + numArgs * sizeof(LPSTR); for (int i = 0; i < numArgs; ++ i) { assert(bufLen > 0); BOOL lpUsedDefaultChar = FALSE; retval = WideCharToMultiByte(CP_ACP, 0, args[i], -1, buffer, bufLen, NULL, &lpUsedDefaultChar); if (!SUCCEEDED(retval)) { LocalFree(result); LocalFree(args); return NULL; } result[i] = buffer; buffer += retval; bufLen -= retval; } LocalFree(args); *pNumArgs = numArgs; return result; }
显然你可以在main()之外使用__argv来访问预先解析的参数向量...