RadAd
2/10/2017 - 3:05 AM

Output a utf8 file to the console

Output a utf8 file to the console

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <string.h>

// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt

int wmain(int argc, const wchar_t* argv[])
{
    int mode = _O_U8TEXT;
    const wchar_t* filename = NULL;

    for (int arg = 1; arg < argc; ++arg)
    {
        if (_wcsicmp(argv[arg], L"/U") == 0)
            mode = _O_U16TEXT;
        else
            filename = argv[arg];
    }

    if (filename == NULL)
    {
        wprintf(L"Usage: ConUtf8 [/U] <filename>\n");
        wprintf(L"  /U - output in UTF16\n");
        return 1;
    }

    _setmode(_fileno(stdout), mode);

    FILE* f = NULL;
    if (_wcsicmp(filename, L"-") == 0)
    {
        f = stdin;
        _setmode(_fileno(stdin), _O_U8TEXT);
    }
    else
    {
        errno_t e = _wfopen_s(&f, filename, L"rt+, ccs=utf-8");
        if (e != 0)
        {
            fwprintf(stderr, L"Error opening file \"%s\": %s\n", filename, _wcserror(e));
            return 1;
        }
    }

    while (1)
    {
        unsigned short cin = fgetwc(f);
        if (cin == WEOF)
        {
            if (feof(f))
                break;
            else
                fputwc(L'?', stdout);
        }
        else
            fputwc(cin, stdout);
    }

    if (f != stdin)
        fclose(f);

    return 0;
}