【问题标题】:Save an unsigned char vector one by one一个一个地保存一个 unsigned char 向量
【发布时间】:2018-06-06 21:41:16
【问题描述】:
#include "stdafx.h"
#include "Compiler.h"
#include <fstream>

int main() {
    std::ofstream output("file.bin", std::ios::binary | std::ios::trunc);
    if(output.fail()) {
        return 1;
    }
    std::vector<unsigned char> f = Runtime::convert_line_to_instructions("rt_reg str Hello");
    for(unsigned char i : f) {
        //output.write(reinterpret_cast<char*>&i, sizeof(unsigned short)); doesn't work here.
    }
    std::cerr << "Program Compiled!" << std::endl;
    while(true);
    return 0;
}

如何将无符号字符向量保存到文件中?我尝试了几种解决方案(包括被注释掉的那个),但都没有奏效。

*convert_line_to_instructions 也返回一个无符号字符向量。

【问题讨论】:

  • 如果数据是unsigned char 的简单数组,您将如何保存数据?
  • sizeof(unsigned short)为什么要用short来表示char的大小?
  • @PaulMcKenzie 真的一样。您也可以使用范围循环解析数组。
  • output &lt;&lt; i;完成
  • @manni66 似乎不起作用。文件大小仍为 0 字节。

标签: c++ vector char unsigned


【解决方案1】:

使用output.put(i);,因为它一次需要一个字符。

但你真的很想跳过 for 循环,只需一次写入整个向量:

output.write(f.data(), f.size());

【讨论】:

  • 文件大小还是0字节。
  • 程序结束时有一个无限循环,因此您永远不会将输出刷新到文件中。因此,当您中止程序时,数据会丢失。
【解决方案2】:

它是一个 fstream,因此您可以使用 iostream 运算符,例如 &lt;&lt;

#include <fstream>
#include <iostream>
#include <vector>

int main(const int argc, const char* argv[]) {
    std::ofstream output{"file.bin", std::ios::binary | std::ios::trunc};
    if (output.fail())
        return 1;

    std::vector<unsigned char> input = {'r', 't', '_', 'r', 'e', 'g', ' ',
                                        's', 't', 'r', ' ', 'H', 'e', 'l',
                                        'l', 'o'};

    for (const auto i : input)
        output << i;

    return 0;
}

更简洁的方法是使用带有迭代器的 STL 算法:

std::copy(begin(input), end(input), std::ostreambuf_iterator<char>(output));

ostreambuf_iterator&lt;char&gt; 是轻量级的、缓冲的,并且不执行格式化。

【讨论】:

  • 即使您使用std::ios::binary 打开文件,您的代码也不会写入binarystackoverflow.com/questions/8277485/…
  • @Brandon 如所列,它确实写二进制文件,我有一个十六进制转储来证明它。问题是,如果您弄乱了输出格式,则不能保证写入二进制数据。如果你不这样做,那么它的工作原理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多