0

I have a file.txt encoded in gbk, I read some bytes through ifstream::read and store them into a char buffer, then I want to print every word in the buffer in gbk.

I assume wchar_t is needed here, so I do it like this:

int main()
{
    ifstream ifs("./file.txt");
    char buf[256];
    ifs.read(buf, 255);

    wchar_t wbuf[256];
    mbstowcs( wbuf, buf, 255);
    for (int i = 0; i < wcslen(wbuf); i++)
        wprintf(L"%c ", wbuf[i]);

}

Am I doing it right? Or any better idea to do the job?

Thanks.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
Alcott
  • 17,905
  • 32
  • 116
  • 173

1 Answers1

2

Have you tried using the wide-char specializations? (ifstream and wifstream are template specializations of basic_ifstream over char and wchar_t respectively.)

wifstream wifs("./file.txt");
wifs.imbue(locale("zh_CN.GBK"));
wchar_t wbuf[256];
wifs.read(buf, 255);
ephemient
  • 198,619
  • 38
  • 280
  • 391