cpp read binary file code example

Example: write and read string binary file c++

#include <cstring>
#include <iostream>
#include <fstream>
#include <string>

struct player_data
{
  std::string name;
  int score;
};

int main()
{

  std::ofstream savefile("score.dat", std::ios_base::binary);
  if(savefile.good())
  {
    player_data Player1;
    Player1.name = "John Doell";
    Player1.score = 55;
    savefile.write(Player1.name.c_str(),Player1.name.size()); // write string to binary file
    savefile.write("\0",sizeof(char)); // null end string for easier reading
    savefile.write(reinterpret_cast<char*>(&Player1.score),sizeof(Player1.score)); // write int to binary file
    savefile.close();
  }

  std::ifstream loadfile("score.dat", std::ios_base::binary);
  if(loadfile.good())
  {
    player_data Player1;
    std::getline(loadfile,Player1.name,'\0'); // get player name (remember we null ternimated in binary)
    loadfile.read((char*)&Player1.score,sizeof(Player1.score)); // read int bytes
    std::cout << "Player1 name: " << Player1.name << std::endl;
    std::cout << "Player1 score: " << Player1.score << std::endl;
  }

  return 0;
}

Tags:

Cpp Example