Created
April 20, 2018 23:42
-
-
Save Xyene/2d90cf266710269e197f1869cb44aff7 to your computer and use it in GitHub Desktop.
Port of Python's `subprocess.list2cmdline` to C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MAX_CMDLINE 8191 | |
wchar_t result[MAX_CMDLINE]; | |
memset(result, 0, sizeof(result)); | |
BOOL needquote = FALSE; | |
for (int i = 2; i < argc; i++) { | |
wchar_t *arg = argv[i]; | |
wprintf(L"arg %d = %ls\n", i, arg); | |
size_t len = wcslen(arg); | |
wchar_t bs_buf[MAX_CMDLINE]; | |
memset(bs_buf, 0, sizeof(bs_buf)); | |
BOOL bs_buf_empty = TRUE; | |
if (wcslen(result)) | |
wcscat(result, L" "); | |
needquote = len ? FALSE : TRUE; | |
for (int j = 0; j < len; j++) { | |
if (arg[j] == L' ' || arg[j] == L'\t') { | |
needquote = TRUE; | |
break; | |
} | |
} | |
if (needquote) { | |
result[wcslen(result)] = L'"'; | |
} | |
for (int j = 0; j < len; j++) { | |
wchar_t c = arg[j]; | |
switch (c) { | |
case L'\\': | |
bs_buf[wcslen(bs_buf)] = c; | |
break; | |
case L'"': | |
for (int k = 0; k < wcslen(bs_buf) * 2; k++) { | |
wcscat(result, L"\\"); | |
} | |
memset(bs_buf, 0, sizeof(bs_buf)); | |
wcscat(result, L"\\\""); | |
break; | |
default: | |
if (wcslen(bs_buf)) { | |
wcscat(result, bs_buf); | |
memset(bs_buf, 0, sizeof(bs_buf)); | |
} | |
result[wcslen(result)] = c; | |
} | |
} | |
if (wcslen(bs_buf)) { | |
wcscat(result, bs_buf); | |
} | |
if (needquote) { | |
wcscat(result, bs_buf); | |
wcscat(result, L"\""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment