// writing to a binary file
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
client c; //Assuming a class called client already exists
ofstream outf(“credit.dat", ios::out|ios::ate);
cout<<“Enter account #(1-100, 0 to end)”<<endl;
cin>>c.acctNo;
while(c.acctNo > 0 && c.acctNo <= 100)
{
cout<<“enter name of the account: ”<<endl;
cin>>c.name;
cout<<"Enter balance of the account: ";
cin>>c.bal;
outf.seekp((c.acctNo-1)*sizeof(client)); //position from beg
outf.write((char*)&c, sizeof(client));
cout<<“Enter acct #”<<endl;
cin>>c.acctNo;
}
return 0;
}
outf.seekp sets the position where the stream will continue to put data.
outf.write writes the data in the first arhumen, from it to it+second argument, meanin it puts sizeof(client) chars sarting from c
(char*)& means that the data is type-casted to a char pointer refernce.
(char*)& means that the data is type-casted to a char pointer refernce.
Not in this case, the & symbol is used to get the memory address of a variable, and then that value is cast as a char*, i.e. a pointer to a character. The write function in line 23 expects a char* as its first argument, that is the reason for the cast.