使用std :: ifstream,std :: istream_iterator和std :: copy未读取整个文件。

5

我有以下代码,我一直在一个188字节的文件上使用它:

std::ifstream is("filename", std::ios::binary);

std::vector<uint8_t> buffer;
std::istream_iterator<uint8_t> i_input(is);
std::copy(i_input, std::istream_iterator<uint8_t>(),
          std::back_inserter(buffer));

std::cout << buffer.size();

然而它只读取了188字节中的186字节。

我已经在十六进制编辑器中以及使用ls -al确认了文件大小。


1
我可以确认这一点。文件大小为368字节,向量大小仅为312。GCC版本是gcc (Debian 4.4.5-8) 4.4.5 - Some programmer dude
2个回答

13

我不知道为什么,默认情况下似乎跳过空格。你需要使用 noskipws 来禁用它:

is >> std::noskipws;

这就是我的全部内容了。虽然我觉得在二进制模式下打开流时跳过空格很奇怪。 - Some programmer dude
2
@JoachimPileborg:这与二进制模式无关。您正在使用格式化提取,它会进行各种混淆和跳过。可以说,将格式化提取到char中是读取原始文件的最糟糕的方式! - Kerrek SB
@KerrekSB 你说得对。我想可能是因为我太早了,没能好好思考。 - Some programmer dude
哦!这很有道理,令人沮丧的是我阅读的地方没有记录。 - Rory Hart

9
什么是最后两个字节?此外,您不需要使用istream_iterator读取这样的二进制数据。那太过于复杂了,而且可能比使用streambuf更慢。
请参阅wilhelmtell的很好的答案中的示例:
#include<iterator>
// ...

std::ifstream testFile("testfile", std::ios::in | std::ios::binary);
std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)),
                               std::istreambuf_iterator<char>());

谢谢!我想我会转换到这种方法。 - Rory Hart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接