2014-10-27 119 views
3

我讀an answer here展示瞭如何用下面的(二)班輪讀取整個流成的std :: string:如何將整個流讀入std :: vector?

std::istreambuf_iterator<char> eos;  
std::string s(std::istreambuf_iterator<char>(stream), eos); 

對於做類似的讀取二進制流的東西變成std::vector,爲什麼不能」我簡單地用uint8_tstd::string替換charstd::vector

auto stream = std::ifstream(path, std::ios::in | std::ios::binary);  
auto eos = std::istreambuf_iterator<uint8_t>(); 
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos); 

上面產生一個編譯器錯誤(VC2013):

1> d:\非SVN \ C++ \庫\ I \文件\ filereader.cpp(62):錯誤C2440: '':不能從 轉換 '的std :: basic_ifstream>' 到 '的std :: istreambuf_iterator>' 1>
其中1> [1> _Elem = uint8_t 1> 1>
沒有構造可以採取源類型或構造函數過載 分辨率不明確

+0

'char'和'uint8_t'不是你的編譯器同樣的事情。嘗試使用'char'來代替。 – cdhowie 2014-10-27 14:08:16

+0

@cdhowie'uint8_t'是'unsigned char',所以是的,在任何一臺計算機上都不一樣;)但是,這可能是一個模糊的轉換,因爲'ifstream'的輸出是'char''。 – aruisdante 2014-10-27 14:09:54

+0

是的,它適用於char,但uint8_t無論如何都是unsigned char。 – Robinson 2014-10-27 14:10:00

回答

9

只有一種類型不匹配。 ifstream只是一個typedef:

typedef basic_ifstream<char> ifstream; 

所以,如果你想使用一個不同的基本類型,你只需要告訴它:

std::basic_ifstream<uint8_t> stream(path, std::ios::in | std::ios::binary);  
auto eos = std::istreambuf_iterator<uint8_t>(); 
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos); 

這對我的作品。

或者,由於迪特馬爾說,這可能是一個有點粗略,你可以這樣做:基於錯誤信息,

auto stream = std::ifstream(...); 
std::vector<uint8_t> data; 

std::for_each(std::istreambuf_iterator<char>(stream), 
       std::istreambuf_iterator<char>(), 
       [&data](const char c){ 
        data.push_back(c); 
       }); 
+0

啊。當然。謝謝。 – Robinson 2014-10-27 14:11:27

+0

這真的很有意思!它可能會編譯,但我無法想象它會立即運行:爲char或wchar_t以外的字符類型創建一個流當然不必立即工作,因爲必需的許多方面不必提供。對於特定的需求,我希望至少缺少'std :: codecvt '(我不確定是否真的需要其他方面)。 – 2014-10-27 14:18:08

+0

如果不應該開箱即用,我想我不應該這樣做。我想要的是區分二進制流和二進制數據以及文本流和文本數據。所以我打算使用uint8_t來表示二進制數據,而使用char來表示文本。我想這是所有東西都使用char的習慣用法... – Robinson 2014-10-27 14:20:20

5

ifstreamchar的流,而不是uint8_t。您需要使用basic_ifstream<uint8_t>istreambuf_iterator<char>來匹配類型。

由於該庫只需要支持charwchar_t的流,因此前者可能無法正常工作。所以你可能想要istreambuf_iterator<char>

+0

...並創建一個'std :: basic_ifstream '是非常不平凡的! – 2014-10-27 14:14:10

+0

@DietmarKühl:好點。我通常會避免I/O庫的深度,因此無法準確記住它支持的內容。 – 2014-10-27 14:22:19

相關問題