在 C++ 中将二进制数据写入 fstream

Writing binary data to fstream in c++(在 C++ 中将二进制数据写入 fstream)
本文介绍了在 C++ 中将二进制数据写入 fstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些结构要写入二进制文件.它们由来自 cstdint 的整数组成,例如 uint64_t.有没有办法将它们写入二进制文件,而不需要我手动将它们拆分为 char 数组并使用 fstream.write() 函数?

I have a few structures I want to write to a binary file. They consist of integers from cstdint, for example 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?

我幼稚的想法是 c++ 会发现我有一个二进制模式的文件,而 << 会将整数写入该二进制文件.所以我尝试了这个:

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. 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;
}

但是,这会将字符串65535"写入文件.

However, this wrote the string "65535" to the file.

我能否以某种方式告诉 fstream 切换到二进制模式,例如如何使用 << 更改显示格式?std::hex?

Can I somehow tell the fstream to switch to binary mode, like how I can change the display format with << std::hex?

如果以上所有这些都失败了,我需要一个将任意 cstdint 类型转换为 char 数组的函数.

Failing all that above I'd need a function that turns arbitrary cstdint types into char arrays.

我并不真正关心字节顺序,因为我会使用相同的程序来读取它们(在下一步中),所以它会取消.

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.

推荐答案

可以,这就是 std::fstream::write 用于:

Yes you can, this is what std::fstream::write is for:

#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.
}

这篇关于在 C++ 中将二进制数据写入 fstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)