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
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
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;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us