how to read binary data from file in c++ 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());
savefile.write("\0",sizeof(char));
savefile.write(reinterpret_cast<char*>(&Player1.score),sizeof(Player1.score));
savefile.close();
}
std::ifstream loadfile("score.dat", std::ios_base::binary);
if(loadfile.good())
{
player_data Player1;
std::getline(loadfile,Player1.name,'\0');
loadfile.read((char*)&Player1.score,sizeof(Player1.score));
std::cout << "Player1 name: " << Player1.name << std::endl;
std::cout << "Player1 score: " << Player1.score << std::endl;
}
return 0;
}