我試圖在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。
首先,Windows需要UTF16LE,而不是UTF8。 ...我認爲在繼續之前,你應該放慢腳步,更詳細地理解字符集。 – deviantfan