Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WriteFile and WriteConsole

Tags:

c

winapi

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);
}
like image 384
Josh Avatar asked Dec 07 '25 06:12

Josh


1 Answers

I tested the output of wprintf which seems to convert the string to ASCII before printing it.

So current acceptable solution:

  1. Convert str to ASCII
  2. Print str with WriteFile

Much simpler code too.

like image 103
Josh Avatar answered Dec 08 '25 21:12

Josh