2011-02-17 265 views
10

我UT8文本文件時,即時閱讀使用簡單:C++如何寫/ Unicode中讀取的ofstream/UTF8

ifstream in("test.txt"); 

現在我喜歡創造新的文件,無線本地環路是UT8編碼或Unicode 如何我與流或其他? 這創建了我的ansi編碼。

ofstream out(fileName.c_str(), ios::out | ios::app | ios::binary); 
+0

你是什麼意思UTF8是不是Unicode? – 2011-02-17 08:38:53

+0

請包括一個最小但完整的代碼示例,展示您描述的行爲。 – 2011-02-17 08:39:38

回答

5

好吧,關於便攜式的變種。如果你使用C++11標準很容易(因爲有很多額外的包括像"utf8",永久解決這個問題)。

但是,如果你想使用多平臺的代碼與舊標準,您可以使用此方法與流寫:

  1. Read the article about UTF converter for streams
  2. 來源添加stxutif.h到項目上面
  3. 以ANSI模式打開文件,並將BOM添加到文件的開頭,如下所示:

    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(); 
    
  4. 然後打開該文件作爲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...