2014-10-27 103 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