[英]std::fstream different behavior on msvc and g++ with utf-8
std::string path("path.txt");
std::fstream f(path);
f.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
std::string lcpath;
f >> lcpath;
從path.txt
上的path.txt
讀取 utf-8 文本失敗,在 Windows 上使用 MSVC 編譯器,因為lcpath
無法將路徑理解為 utf-8。
使用 g++ 編譯時,以下代碼在 linux 上正常工作。
std::string path("path.txt");
std::fstream ff;
ff.open(path.c_str());
std::string lcpath;
ff>>lcpath;
默認情況下,windows(MSVC) 上的fstream
是否僅假設 ascii?
在第一個片段中,如果我使用wstring
更改string
並使用wfstream
更改fstream
,則wfstream
lcpath
在 Windows 上獲得正確的值。
編輯:如果我使用MultiByteToWideChar()
轉換讀取的lcpath
,我會得到正確的表示。 但是為什么我不能在 Windows 上直接將 UTF-8 字符串讀入std::string
中?
注入打開的文件可能是有問題的:
http://www.cplusplus.com/reference/fstream/filebuf/imbue/
如果 loc 與文件流緩沖區當前使用的區域設置不同,則內部位置指針指向文件的開頭,或者其編碼與狀態無關。 否則,它會導致未定義的行為。
這里的問題是當一個文件被打開並且文件中有一個 BOM 標記時,它通常會被當前安裝的本地文件從文件中讀取。 因此position pointer
不再位於文件的開頭,我們有未定義的行為。
為了確保您的本地設置正確,您必須在打開文件之前進行設置。
std::fstream f;
f.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
std::string path("path.txt");
f.open(path);
std::string lcpath;
f >> lcpath;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.