I want to be able to use WriteFile or WriteConsole so the following 3 functions work:
> Output.exe
> Output.exe > File.txt & type File.txt
> for /F "tokens=*" %A in ('Output.exe') do @echo %A
I managed to get the first two working with my current code. But now the for loop outputs: The system cannot write to the specified device.
I guess it doesn't like my BOM. How can I make my code work with the for loop?
Here's my current code.
DWORD dwBytesWritten;
DWORD dwConMode;
BOOL bRedirectedToFile;
WCHAR str[] = L"Hello World";
bRedirectedToFile = !GetConsoleMode(hStdOut, &dwConMode);
if (bRedirectedToFile)
{
LONG zero = 0;
DWORD pos = SetFilePointer(hStdOut, 0, &zero, FILE_CURRENT);
if (pos == 0)
{
WORD Unicode = ((BYTE*)L"A")[0] == 0 ? 0xfffe : 0xfeff;
WriteFile(hStdOut, &Unicode, 2, &dwBytesWritten, 0);
}
WriteFile(hStdOut, str, lstrlen(str) * sizeof(WCHAR), &dwBytesWritten, 0);
}
else
{
WriteConsole(hStdOut, str, lstrlen(str), &dwBytesWritten, 0);
}
I tested the output of wprintf which seems to convert the string to ASCII before printing it.
So current acceptable solution:
str to ASCIIstr with WriteFileMuch simpler code too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With