私の誠実な努力にもかかわらず、ここでバグを見つけることができないようです. ベクトルを ofstream に書き込んでいます。ベクトルにはバイナリ データが含まれます。しかし、なぜか空白文字(0x10、0x11、0x12、0x13、0x20)が書かれているはずなのに読み飛ばされてしまう。
イテレータと直接の ofstream::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 は省略されています。これは、表向きは空白であるためです。
どんな提案でも大歓迎です。