STL and UTF-8 file input/output. How to do it?

前端 未结 5 421
醉酒成梦
醉酒成梦 2020-12-06 08:15

I use wchar_t for internal strings and UTF-8 for storage in files. I need to use STL to input/output text to screen and also do it by using full Lithua

5条回答
  •  Happy的楠姐
    2020-12-06 09:00

    Well, after some testing I figured out that FILE is accepted for _iobuf (in the w*fstream constructor). So, the following code does what I need.

    #include 
    #include 
    #include 
    #include 
    //For writing
        FILE* fp;
        _wfopen_s (&fp, L"utf-8_out_test.txt", L"w");
        _setmode (_fileno (fp), _O_U8TEXT);
        wofstream fs (fp);
        fs << L"ąfl";
        fclose (fp);
    //And reading
        FILE* fp;
        _wfopen_s (&fp, L"utf-8_in_test.txt", L"r");
        _setmode (_fileno (fp), _O_U8TEXT);
        wifstream fs (fp);
        wchar_t array[6];
        fs.getline (array, 5);
        wcout << array << endl;//For debug
        fclose (fp);
    This sample reads and writes legit UTF-8 files (without BOM) in Windows compiled with Visual Studio 2k8.

    Can someone give any comments about portability? Improvements?

提交回复
热议问题