文件流矢量,文件大小错误

问题描述

我找到了很多有关该问题的文章,但是没有一篇文章对此进行了足够详尽的解释,并且我对流技术仍然缺乏经验: 我想将文件流式传输到矢量,并且此矢量已经定义并且包含一些数据。

代码段似乎有效(无效):

std::ifstream fileInputStream(path.wc_str(),std::ios::binary);
//byteVector contains some data and is of type: std::vector<unsigned char>*
byteVector->insert(byteVector->end(),std::istream_iterator<unsigned char>(fileInputStream),std::istream_iterator<unsigned char>());

在本文中,我找到了一种获取文件长度的方法Using C++ filestreams (fstream),how can you determine the size of a file?

std::ifstream fileInputStream;
fileInputStream.open(path.wc_str(),std::ios::in | std::ios::binary);
fileInputStream.ignore(std::numeric_limits<std::streamsize>::max());
std::streamsize fileLength = fileInputStream.gcount();
fileInputStream.clear();   //  Since ignore will have set eof.
fileInputStream.seekg(0,std::ios_base::beg);

如果我比较第一个代码段的vector-> size和第二个代码段的fileLength,则我的向量大约短2KB。

我想避免将数据从一个缓冲区复制到另一个缓冲区,因此,如果我需要更多的缓冲区来读取所有数据,我希望使用std :: move或类似的东西。有人知道我的第一个代码片段出了什么问题,或者如何以另一种方式完成此操作?

我应该将文件读入另一个矢量缓冲区并将该矢量移到我的第一个缓冲区的末尾吗?

解决方法

std::istream_iterator<unsigned char>是一种格式的输入迭代器,它会跳过空格,这就是向量很短的原因。

改为使用std::istreambuf_iterator<char>,它逐字读取数据。

请注意,这两个迭代器之间template参数的含义完全不同。在后一种情况下,它是std::char_traits<>解码的符号类型(例如,您可能希望将utf-8编码的文件解码为wchar_t的序列)。 std::istreambuf_iterator<char>进行身份解码。 C ++流一直使用char类型表示二进制数据(例如,参见std::ostream::write)。