How to set file encoding format to UTF8 in C++

后端 未结 4 944
慢半拍i
慢半拍i 2021-01-13 03:59

A requirement for my software is that the encoding of a file which contains exported data shall be UTF8. But when I write the data to the file the encoding is always ANSI. (

4条回答
  •  日久生厌
    2021-01-13 04:18

    AFAIK, fprintf() does character conversions, so there is no guarantee that passing UTF-8 encoded data to it will actually write the UTF-8 to the file. Since you already converted the data yourself, use fwrite() instead so you are writing the UTF-8 data as-is, eg:

    DWORD dwCount = MultiByteToWideChar( CP_ACP, 0, line.c_str(), line.length(), NULL, 0 );  
    if (dwCount == 0) continue;
    
    std::vector utf16Text(dwCount);  
    MultiByteToWideChar( CP_ACP, 0, line.c_str(), line.length(), &utf16Text[0], dwCount );  
    
    dwCount = WideCharToMultiByte( CP_UTF8, 0, &utf16Text[0], utf16Text.size(), NULL, 0, NULL, NULL );  
    if (dwCount == 0) continue;
    
    std::vector utf8Text(dwCount);  
    WideCharToMultiByte( CP_UTF8, 0, &utf16Text[0], utf16Text.size(), &utf8Text[0], dwCount, NULL, NULL );  
    
    fwrite(&utf8Text[0], sizeof(CHAR), dwCount, pOutputFile);  
    fprintf(pOutputFile, "\n");  
    

提交回复
热议问题