簡體   English   中英

std::fstream 在 msvc 和 g++ 上使用 utf-8 的不同行為

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM