Search code examples
cwindowsstdinutf

How to write non-ascii from stdin to file properly


#include <stdio.h>
#include <windows.h>


int main(int argc, char** argv)
{
    DWORD bytes_read;
    char buffer[65536];
    LPSTR str;

    ReadFile(GetStdHandle(STD_INPUT_HANDLE), buffer, 65536, &bytes_read, NULL);
    str = malloc(bytes_read);
    memcpy(str, buffer, bytes_read);

    FILE *f = fopen("file.txt", "w");
    fprintf(f, "stdin: %s", str);
    fprintf(f, "hardcoded: %s\n", "á");
    fclose(f);

    return 0;
}

when run in powershell via echo á|.\Program.exe, content of file.txt is:

stdin: ? ýýýýhardcoded: á

I'm interested in replacing question mark with proper character retrieved from stdin


Solution

  • Stdin is apparently using CP437 charset. Reloading file with this encoding shows correct character