Answers for "c++ write to binary file"

PHP
7

write a binary file c

FILE *write_ptr;

write_ptr = fopen("test.bin","wb");  // w for write, b for binary

fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer
Posted by: Guest on May-15-2020
-1

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;
}
Posted by: Guest on April-28-2021

Browse Popular Code Answers by Language