2015-06-22 32 views
1

我試圖在Windows上使用中文字符創建文件。整個路徑在變量「std :: string originalPath」中,但是,我有一個字符集問題,我根本無法理解要克服。使用中文字符時錯誤的文件名

我寫了下面的代碼:

#include <iostream> 
#include <boost/locale.hpp> 
#include <boost/filesystem/fstream.hpp> 
#include <windows.h> 

int main(int argc, char *argv[]) 
{ 

    // Start the rand 
    srand(time(NULL)); 

    // Create and install global locale 
    std::locale::global(boost::locale::generator().generate("")); 
    // Make boost.filesystem use it 
    boost::filesystem::path::imbue(std::locale()); 

    // Check if set to utf-8 
    if(std::use_facet<boost::locale::info>(std::locale()).encoding() != "utf-8"){ 
     std::cerr << "Wrong encoding" << std::endl; 
     return -1; 
    } 

    std::string originalPath = "C:/test/s/一.png"; 

    // Convert to wstring (**WRONG!**) 
    std::wstring newPath(originalPath.begin(), originalPath.end()); 

    LPWSTR lp=(LPWSTR)newPath.c_str(); 
    CreateFileW(lp,GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | 
      FILE_SHARE_WRITE,  NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); 

    return 0; 

} 

運行它,但是,我得到的文件夾內的 「C:\測試\ S」 名 「¦ㅈタ巴紐」 的文件,而不是「一.png」,我想要的。我發現克服這個唯一的辦法是交流線路

std::string originalPath = "C:/test/s/一.png"; 

// Convert to wstring (**WRONG!**) 
std::wstring newPath(originalPath.begin(), originalPath.end()); 

簡單

std::wstring newPath = L"C:/test/s/一.png"; 

在這種情況下,文件「一巴紐」完美地出現在文件夾「C裏面:\測試\的」。儘管如此,我不能這樣做,因爲軟件從std :: string變量中獲取路徑。我認爲從std :: string到std :: wstring的轉換是以錯誤的方式執行的,但是,正如可以看到的,我在試圖理解這個邏輯時遇到了深刻的問題。我詳盡地閱讀和研究Google,閱讀了許多定性的文章,但是我所有的嘗試似乎都沒用。我嘗試了MultiByteToWideChar函數和boost :: filesystem,但都沒有任何幫助,當寫入文件夾時我無法獲得正確的文件名。

我還在學習,所以我非常抱歉,如果我犯了一個愚蠢的錯誤。我的IDE是Eclipse,它設置爲UTF-8。

+0

首先,Windows需要UTF16LE,而不是UTF8。 ...我認爲在繼續之前,你應該放慢腳步,更詳細地理解字符集。 – deviantfan

回答

2

您需要將UTF-8字符串實際轉換爲UTF-16。爲此,您必須查找如何使用boost::locale::conv或(僅在Windows上)使用MultiByteToWideChar函數。

std::wstring newPath(originalPath.begin(), originalPath.end());將無法​​正常工作,它會將所有字節逐一複製並將其轉換爲wchar_t。

0

謝謝你的幫助,roeland。最後,我設法找到了解決方案,並簡單地使用了以下庫:「http://utfcpp.sourceforge.net/」。我使用函數「utf8 :: utf8to16」將我的原始UTF-8字符串轉換爲UTF-16,這樣Windows就可以正確顯示中文字符。

相關問題