简体   繁体   中英

Reading and Writing to a Binary File in C++

I have 2 variables, string and integer, and i want to write both data into a binary file. I've searched about it on google, some of them are using memcpy, fstream, and the others. However, what I've found is just a way to store data with the same data type like integer only or string only. I want to store both string and integer data types in one binary file, and I don't declare the variable inside a struct.

How i can do this in C++?

Using fstream is the simplest way:

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

However, you need to know that object representation is not guaranteed to be the same depending the OS, compiler...

This is guaranteed to work if you use it with the same compiler, same version and same OS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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