文件流到矢量,文件大小错误
filestream to vector, filesize wrong
我找到了很多关于这个问题的文章,但是 none 对此进行了足够详细的解释,我对流仍然没有经验:
我想将一个文件流式传输到一个向量,这个向量已经定义并包含一些数据。
此代码段似乎有效(但无效):
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>
,它逐字读取数据。
请注意,这两个迭代器的模板参数的含义完全不同。在后一种情况下,它是由 std::char_traits<>
(e.g. you may want to decode a utf-8 encoded file as sequence of wchar_t
). std::istreambuf_iterator<char>
does identity decoding. C++ streams have been using char
type for representing binary data (see std::ostream::write
解码的符号类型。例如。
我找到了很多关于这个问题的文章,但是 none 对此进行了足够详细的解释,我对流仍然没有经验: 我想将一个文件流式传输到一个向量,这个向量已经定义并包含一些数据。
此代码段似乎有效(但无效):
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>
,它逐字读取数据。
请注意,这两个迭代器的模板参数的含义完全不同。在后一种情况下,它是由 std::char_traits<>
(e.g. you may want to decode a utf-8 encoded file as sequence of wchar_t
). std::istreambuf_iterator<char>
does identity decoding. C++ streams have been using char
type for representing binary data (see std::ostream::write
解码的符号类型。例如。