I came across this code for making .dat files in c++.
These two lines i couldn’t understand.. How does these work?
outfile.write(reinterpret_cast<char*>(&pers), sizeof(pers));
ofstream outfile("PERSON.DAT",ios::app| ios::binary);
#include <fstream> //for file streams
#include <iostream>
using namespace std;
class person //class of persons
{
protected:
char name[80]; //person’s name
short age; //person’s age
public:
void getData() //get person’s data
{
cout <<"Enter name: "; cin >> name;
cout <<"Enter age: "; cin >> age;
}
};
int main()
{
char ch;
person pers; //create a person
ofstream outfile("PERSON.DAT",ios::app| ios::binary);
do {
pers.getData(); //get data for person
outfile.write(reinterpret_cast<char*>(&pers), sizeof(pers));
cout <<"Enter another person (y/n)? ";
cin >> ch;
} while (ch == 'y');
//create ofstream object
//write to it
return 0;
}
Starting with this second line, this creates an output file stream which then opens a file called “PERSON.DAT” using a combination of two modes; append and binary. This means that any data sent to the output stream will be appended to the existing data in the file, you are effectively adding data to the file rather than overwriting it. The binary mode specifies that any data written to the file will be interpreted as-is. In Windows there is a mode called text mode, in which certain characters such as ‘\n’ are translated into their Windows equivalents. Binary mode is the standard mode, it just means that whatever you send to the output stream is written without modification.
This command writes the pers object to the output file. the write() method expects two parameters; the first is a pointer to a series of bytes to be written to the file and the second is an integer indicating the number of bytes from the series to be written. The reinterpret_cast() function will cast the pointer to the person object from person* to char*, which is the parameter type required by the write method. sizeof() is simply a function which gets the size of an object in bytes which, as mentioned, is required by write() also.