繁体   English   中英

在 C++ 中读取和写入二进制文件

[英]Reading and Writing to a Binary File in C++

我有 2 个变量,字符串和 integer,我想将这两个数据写入二进制文件。 我在 google 上搜索过,其中一些正在使用 memcpy、fstream 等。 但是,我发现的只是一种存储具有相同数据类型的数据的方法,例如仅 integer 或仅字符串。 我想将字符串和 integer 数据类型存储在一个二进制文件中,并且我没有在结构中声明变量。

我如何在 C++ 中做到这一点?

使用fstream是最简单的方法:

#include <fstream>
#include <string>

int main()
{
  int number = 3;
  std::string str = "my_str";

  // Writing
  std::fstream out("file", std::ios::binary | std::ios::out);

  out << number << str;

  // We are going to open the file again, so we need to close it first
  // We could have opened a new scope instead
  out.close();

  // Reading
  std::fstream in("file", std::ios::binary | std::ios::in);
  in >> number >> str;

  // No need to close the file, it is done thanks to RAII
}

但是,您需要知道 object 表示不保证相同,具体取决于操作系统、编译器......

如果您将它与相同的编译器、相同的版本和相同的操作系统一起使用,这保证可以工作

暂无
暂无

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

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