简体   繁体   English

用c ++将二进制数据写入fstream

[英]Writing binary data to fstream in c++

Question

I have a few structures I want to write to a binary file. 我有一些我想写入二进制文件的结构。 They consist of integers from cstdint, for example uint64_t . 它们由来自cstdint的整数组成,例如uint64_t Is there a way to write those to a binary file that doesn not involve me manually splitting them into arrays of char and using the fstream.write() functions? 有没有办法将这些写入二进制文件,不涉及我手动将它们拆分为char数组并使用fstream.write()函数?

What I've tried 我试过的

My naive idea was that c++ would figure out that I have a file in binary mode and << would write the integers to that binary file. 我天真的想法是,c ++会发现我有一个二进制模式的文件, <<会将整数写入该二进制文件。 So I tried this: 所以我尝试了这个:

#include <iostream>
#include <fstream>
#include <cstdint>

using namespace std;

int main() {
  fstream file;
  uint64_t myuint = 0xFFFF;
  file.open("test.bin", ios::app | ios::binary);
  file << myuint;
  file.close();
  return 0;
}

However, this wrote the string "65535" to the file. 但是,这会将字符串“65535”写入文件。

Can I somehow tell the fstream to switch to binary mode, like how I can change the display format with << std::hex ? 我可以以某种方式告诉fstream切换到二进制模式,就像我可以用<< std::hex更改显示格式吗?

Failing all that above I'd need a function that turns arbitrary cstdint types into char arrays. 如果不能解决上述问题,我需要一个将任意cstdint类型转换为char数组的函数。

I'm not really concerned about endianness, as I'd use the same program to also read those (in a next step), so it would cancel out. 我并不是真的关心字节序,因为我会使用相同的程序来读取它们(在下一步中),所以它会被取消。

Yes you can, this is what std::fstream::write is for: 是的,你可以,这是std::fstream::write的用途:

#include <iostream>
#include <fstream>
#include <cstdint>

int main() {
  std::fstream file;
  uint64_t myuint = 0xFFFF;
  file.open("test.bin", std::ios::app | std::ios::binary);
  file.write(reinterpret_cast<char*>(&myuint), sizeof(myuint)); // ideally, you should memcpy it to a char buffer.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM