using Read and Write methods to write to a Binary File





This video tutorial teaches you how to use read and write methods with binary file to read and write blocks of data and this tutorial explains how to save an object to a file using write method and then reading and using that object using read method.

source code for this tutorial

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class Person{
char name[80];
int age;
public:
    Person(){
    strcpy(name,"noname");
    age = 0;
    }
   Person(char *name,int age){
    strcpy(this->name,name);
    this->age = age;
    }

    void whoAreYou(){
    cout << "hi am "<<name<<" and i am "<<age<<" nyears old"<<endl;
    }
    void change(){
        strcpy(name,"xxxx");
    age = 1000;
    }

};


int main()
{
Person anil("anil",24);

fstream file("person.bin",ios::binary | ios::in | ios::out | ios::trunc );
if(!file.is_open()){
    cout << "error while opening the file";
}else{
file.write((char *)&anil,sizeof(Person));

file.seekg(0);

Person anjali;
file.read((char *)&anjali,sizeof(Person));

anil.whoAreYou();
anjali.whoAreYou();

anil.change();

anil.whoAreYou();
anjali.whoAreYou();
file.close();
}

   return 0;
}