How to write UTF-8 encoded string to a file in windows, in C ++

I have a string that may or may not contain Unicode characters in it, I'm trying to write this to a file on windows. Below I posted a sample code, my problem is that when I open and read the values ​​back from the windows, they are all interpreted as UTF-16 characters.

char* x = "Fool";
FILE* outFile = fopen( "Serialize.pef", "w+,ccs=UTF-8");
fwrite(x,strlen(x),1,outFile);
fclose(outFile);

char buffer[12];
buffer[11]=NULL;
outFile = fopen( "Serialize.pef", "r,ccs=UTF-8");
fread(buffer,1,12,outFile);
fclose(outFile);

Characters are also interpreted as UTF-16 if I open the file in a text box, etc. What am I doing wrong?

+3
source share
2 answers

, , UTF-8, CRT , Unicode . , UTF-8. :

wchar_t* x = L"Fool";
FILE* outFile = fopen( "Serialize.txt", "w+,ccs=UTF-8");
fwrite(x, wcslen(x) * sizeof(wchar_t), 1, outFile);
fclose(outFile);

:

char* x = "Fool";
FILE* outFile = fopen( "Serialize.txt", "w+,ccs=UTF-8");
fwprintf(outFile, L"%hs", x);
fclose(outFile);
+5

, C++11 ( , "utf8", ).

, :

  • UTF
  • stxutif.h
  • ANSI , :

    std::ofstream fs;
    fs.open(filepath, std::ios::out|std::ios::binary);
    
    unsigned char smarker[3];
    smarker[0] = 0xEF;
    smarker[1] = 0xBB;
    smarker[2] = 0xBF;
    
    fs << smarker;
    fs.close();
    
  • UTF :

    std::wofstream fs;
    fs.open(filepath, std::ios::out|std::ios::app);
    
    std::locale utf8_locale(std::locale(), new utf8cvt<false>);
    fs.imbue(utf8_locale); 
    
    fs << .. // Write anything you want...
    
0

Source: https://habr.com/ru/post/1770426/


All Articles