You may say.
//#DEFINE UNICODE
#include <Windows.h>
int main()
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
LPTSTR msg = TEXT("Hello, World!n");
WriteConsole(hOut, msg, lstrlen(msg), NULL, NULL);
}
This works, as long as STDOUT
is not redirected, as in main > tmp.txt
. Then, WriteConsole()
errors, with the format message “The handle is invalid.”. Then, WriteFile()
should work, so you may say.
WriteFile(hOut, msg, lstrlen(msg), NULL, NULL);
This is great, except if 1) STDOUT
is not redirected, and 2) UNICODE is set. Then it would print H e l l o ,
, because apparently WriteFile()
does not “translate” the characters, it just sends the bytes. Maybe this can be solved by changing the DOS codepage, but it would not to be UTF-16, since Windows calls UTF-16 “UNICODE”. On my computers, the codepages for UTF-16 are not available, so I would not rely on it.
The solution I (ChatGPT 4o) found is to identify if the “file type” of the handle.
if (GetFileType(hOut) == FILE_TYPE_CHAR)
WriteConsole(hOut, msg, lstrlen(msg), NULL, NULL);
else
WriteFile(hOut, msg, lstrlen(msg) * sizeof(TCHAR), NULL, NULL);
Still, is this the proper solution? And if possible, what is the proper way of reading STDIN
, since it suffers from a similar problem?