Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an UTF-8 encoded file containing Chinese characters and output them correctly on console?

I am writing a web crawler to fetch some Chinese web files. The fetched files are encoded in utf-8. And I need to read those file to do some parse, such as extracting the URLs and Chinese Characters. But I found that when I read the file into a std::string variable and output it into the console, the Chinese characters became garbage characters. I applied the boost::regex into the std::string variable and can extract all URLs but Chinese characters.

How can I solves those problems?

P.S. My CPP files are encoded as ANSI by default, the operating system is Win8 in Chinese Language;

like image 763
Bruce Yang Avatar asked Nov 25 '13 14:11

Bruce Yang


People also ask

Can UTF-8 handle Chinese characters?

UTF-8 is a character encoding system. It lets you represent characters as ASCII text, while still allowing for international characters, such as Chinese characters. As of the mid 2020s, UTF-8 is one of the most popular encoding systems.

Is Chinese language UTF-8?

Unicode/UTF-8 characters include: Chinese characters. any non-Latin scripts (Hebrew, Cyrillic, Japanese, etc.) symbols.

Is Simplified Chinese UTF-8?

Simplified Chinese in the Solaris 8 environment provides three locales: zh, zh. UTF-8, and zh. GBK.


1 Answers

This code may help (it was compiled with VC++ 2010). I tested it with an UTF-8 file containing non-latin characters and it seems to work, but I don't know if it will work fine with Chinese characters. Check the following links for more information: _setmode and codecvt_utf8.

#include <iostream>
#include <fstream>
#include <string>
#include <locale>
#include <codecvt>
#include <fcntl.h>
#include <io.h>

using namespace std;    // Sorry for this!

void read_all_lines(const wchar_t *filename)
{
    wifstream wifs;
    wstring txtline;
    int c = 0;

    wifs.open(filename);
    if(!wifs.is_open())
    {
        wcerr << L"Unable to open file" << endl;
        return;
    }
    // We are going to read an UTF-8 file
    wifs.imbue(locale(wifs.getloc(), new codecvt_utf8<wchar_t, 0x10ffff, consume_header>()));
    while(getline(wifs, txtline))
        wcout << ++c << L'\t' << txtline << L'\n';
    wcout << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    // Console output will be UTF-16 characters
    _setmode(_fileno(stdout), _O_U16TEXT);
    if(argc < 2)
    {
        wcerr << L"Filename expected!" << endl;
        return 1;
    }
    read_all_lines(argv[1]);
    return 0;
}

If Chinese characters don't look as expected, make sure the console is using a font that supports UTF-16 (ie. don't use bitmap fonts).

like image 79
Jigsore Avatar answered Oct 12 '22 11:10

Jigsore