When writing Windows applications in C, it’s common to rely on the CommandLineToArgvW function to split the command line into individual arguments. However, this function only works with wide-character (UTF-16) strings. If your application handles ANSI or UTF-8 command lines, you need a compatible bridge.
This article demonstrates how to implement CommandLineToArgvAEx, an ANSI-aware version that supports arbitrary code pages.
CommandLineToArgvAEx converts an ANSI (or UTF-8) command line into a list of arguments (argv[]) by:
- Converting the original ANSI string into a UTF-16 string.
- Calling
CommandLineToArgvWto perform the actual parsing. - Converting each wide-character argument back to the specified code page.
This approach leverages Windows’s built-in parsing logic while preserving compatibility with various encodings.
The function works in three main stages:
-
Conversion to UTF-16
int wlen = MultiByteToWideChar(codepage, 0, lpCmdLine, -1, NULL, 0); LPWSTR lpWideCmdLine = (LPWSTR)LocalAlloc(LMEM_FIXED, wlen * sizeof(WCHAR)); MultiByteToWideChar(codepage, 0, lpCmdLine, -1, lpWideCmdLine, wlen);
-
Parsing with CommandLineToArgvW
int argcW = 0; LPWSTR* argvW = CommandLineToArgvW(lpWideCmdLine, &argcW);
-
Conversion back to ANSI
int alen = WideCharToMultiByte(codepage, 0, argvW[i], -1, NULL, 0, NULL, NULL); argvA[i] = (LPSTR)LocalAlloc(LMEM_FIXED, alen); WideCharToMultiByte(codepage, 0, argvW[i], -1, argvA[i], alen, NULL, NULL);
Each argvA[i] is a separately allocated string that the caller must free using LocalFree.
The main() function retrieves the current console code page using GetConsoleOutputCP() and the full command line using GetCommandLineA(). It then calls CommandLineToArgvAEx to parse it:
UINT cp = GetConsoleOutputCP();
LPCSTR cmd = GetCommandLineA();
int argc = 0;
LPSTR* argv = CommandLineToArgvAEx(cmd, &argc, cp);Finally, it prints each argument and cleans up the allocated memory.
Sample output:
Current code page: 65001
Raw CommandLineA: "example.exe" arg1 "multi word" arg3
Parsed arguments:
[0] example.exe
[1] arg1
[2] multi word
[3] arg3
- ✅ Supports UTF-8, ACP, or any specified code page
- ✅ Uses standard Windows API for correctness
- ✅ Requires no C runtime dependencies beyond
<windows.h>
CommandLineToArgvAEx is a practical wrapper for developers who need consistent argument parsing across encodings in minimal or CRT-free Windows applications. It preserves the behavior of CommandLineToArgvW while adding full ANSI and UTF-8 support — ideal for lightweight tools and custom launchers.