簡體   English   中英

std::basic_fstream<unsigned char> 不適用於 Linux

[英]std::basic_fstream<unsigned char> doesn't work on Linux

basic_fstream<unsigned char>流上調用read()函數時,我在 Linux 上basic_fstream<unsigned char>

basic_fstream<unsigned char> fs;
basic_string<unsigned char> buf(1000, '\0');
fs.open( "/tmp/file.txt", ios::in | ios::binary);
fs.read( &buf[0], 1000);

我跟蹤了它拋出的位置:在函數__check_facet(const _Facet* __f)它拋出__throw_bad_cast()因為__f是 NULL。 __check_facet()依次從underflow()調用,以_M_codecvt作為參數(為 NULL 並導致失敗)。

系統的locale是UTF8,代碼用--std=c++14編譯。 在 Windows 上,這可以正常工作。

可以以某種方式糾正嗎?

標准庫不需要為unsigned char提供方面或語言環境。 標准流的設計僅考慮了char (和wchar_t )。

我建議改用標准的std::ifstream 您可以使用它讀取二進制數據,並將其存儲到unsigned char緩沖區中。 您應該考慮為該緩沖區使用標准std::vector容器而不是std::basic_string

試試這個:

ifstream fs("/tmp/file.txt", ios::binary);
vector<unsigned char> buf(1000);
fs.read( reinterpret_cast<char*>(&buf[0]), 1000);

這將在所有平台上同樣有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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