C++,将向<char>量写入流会跳过空格
C++, Writing vector<char> to ofstream skips whitespace
尽管我付出了最大的努力,但我似乎无法在这里找到错误。我正在给一个流写一个向量。矢量包含二进制数据。然而,由于某种原因,当应该写入空白字符(0x10、0x11、0x12、0x13、0x20)时,它会被跳过。
我尝试过使用迭代器和直接的流::write()。
这是我正在使用的代码。我已经评论掉了我尝试过的其他一些方法。
void
write_file(const std::string& file,
std::vector<uint8_t>& v)
{
std::ofstream out(file, std::ios::binary | std::ios::ate);
if (!out.is_open())
throw file_error(file, "unable to open");
out.unsetf(std::ios::skipws);
/* ostreambuf_iterator ...
std::ostreambuf_iterator<char> out_i(out);
std::copy(v.begin(), v.end(), out_i);
*/
/* ostream_iterator ...
std::copy(v.begin(), v.end(), std::ostream_iterator<char>(out, ""));
*/
out.write((const char*) &v[0], v.size());
}
编辑:还有读回的代码。
void
read_file(const std::string& file,
std::vector<uint8_t>& v)
{
std::ifstream in(file);
v.clear();
if (!in.is_open())
throw file_error(file, "unable to open");
in.unsetf(std::ios::skipws);
std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(),
std::back_inserter(v));
}
这里有一个输入示例:
30 0 0 0 a 30 0 0 0 7a 70 30 0 0 0 32 73 30 0 0 0 2 71 30 0 0 4 d2
这是我读回时得到的输出:
30 0 0 0 30 0 0 0 7a 70 30 0 0 0 32 73 30 0 0 0 2 71 30 0 0 4 d2
正如您所看到的,0x0a被忽略了,表面上是因为它是空白。
如有任何建议,我们将不胜感激。
您忘记在read_file函数中以二进制模式打开文件。
与其乱写矢量<>直接使用boost::archive::binary_oarchive
,boost::serialization
是一种更有效的方法。
我认为"a"被视为新行。我仍然需要考虑如何避开这个问题。
istream_iterator按设计跳过空白。试着用这个:替换你的std::copy
std::copy(
std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>(),
std::back_inserter(v));
istreambuf_editor直接指向streambuf对象,这将避免您看到的空白处理。
相关文章:
- 2D数组来自文本输入,中间有空格
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- EASTL矢量<向量<int>>连续的
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- C++为一串单词添加空格
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 如何打印不带空格的输入整数?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?