Cloud Stack Ninja

I wish to write unicode(UTF-16) text into cmd's stdin and read unicode from its stdout, yet cmd help only says it can output unicode with the /U switch. I notice there are QAs in this site claiming cmd.exe being capable of accepting unicode input, but can't find one that tells me how to do with pipes.

In the code sample below, a file with multilanguage name is created, then cmd.exe /U is used to manipulate it. The cmd process outputs utf-16 text correctly, but still expects ansi input.

STARTUPINFOW si={.cb=sizeof(STARTUPINFOW),.dwFlags=STARTF_FORCEOFFFEEDBACK|STARTF_USESTDHANDLES};
HANDLE hWritePipeStdIn,hReadPipeStdOut;
CreatePipe(&si.hStdInput,&hWritePipeStdIn,0,0);
CreatePipe(&hReadPipeStdOut,&si.hStdOutput,0,0);
SetHandleInformation(si.hStdInput,HANDLE_FLAG_INHERIT,1);
SetHandleInformation(si.hStdOutput,HANDLE_FLAG_INHERIT,1);
si.hStdError=si.hStdOutput;



CloseHandle(CreateFileW(L".\\aaaالعربيةবাংলা日本語한국어ไทยTiếng ViệtYorùbá中文",FILE_WRITE_DATA,0,0,CREATE_ALWAYS,0,0));//create a file with multilanguage name
PROCESS_INFORMATION pi;
wchar_t cmdline[]=L"cmd.exe /U";//set output unicode
CreateProcessW(0,cmdline,0,0,1,CREATE_NO_WINDOW,0,0,&si,&pi);
CloseHandle(si.hStdInput);CloseHandle(si.hStdOutput);
CloseHandle(pi.hProcess);CloseHandle(pi.hThread);


HANDLE hFile=CreateFileW(L".\\a.txt",FILE_WRITE_DATA,FILE_SHARE_READ,0,CREATE_ALWAYS,0,0);
char buf[512];DWORD len;
static char cmdline1[]="dir /b aaa*&exit\r\n";
WriteFile(hWritePipeStdIn,cmdline1,sizeof cmdline1-sizeof*cmdline1,&len,0);//still accepts ansi input
static wchar_t cmdline2[]=L"del aaaالعربيةবাংলা日本語한국어ไทยTiếng ViệtYorùbá中文&exit\r\n";
//WriteFile(hWritePipeStdIn,cmdline2,sizeof cmdline2-sizeof*cmdline2,&len,0);//can't use this. how to delete the file using cmd?
while(ReadFile(hReadPipeStdOut,buf,sizeof buf,&len,0))WriteFile(hFile,buf,len,&len,0);//a.txt is filled with legit UTF-16 text from the dir command
CloseHandle(hFile);


Read more here: https://stackoverflow.com/questions/64393231/piping-unicode-text-into-cmd-exe

Content Attribution

This content was originally published by elflyao at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: