In: Computer Science
HW_6d - Write a struct object to a binary file.
binary file named: critters.bin
each cat.
Record written to file. (see output)
/* OUTPUT
Enter 3 cat records.
Enter information about a cat:
NAME: Tom
AGE: 5
Enter information about a cat:
NAME: Fluffy
AGE: 3
Enter information about a cat:
NAME: Sweet Pea
AGE: 2
Record written to file.
Press any key to continue . . . */
Please make the code based on C++, and make a description for each code.
C++ code:
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
//Defining the struct
struct Cat{
string name;
int age;
}c[3]; //One structure object to contain 3 cats
int main(){
ofstream wf("critters.bin", ios::out | ios::binary); //opening the file in output mode
if(!wf) {
cout << "Cannot open file!" << endl;
return 1;
}
cout<<"Enter 3 cat records."<<endl;
//taking values from user
int i = 0;
while(i<3){
cout << "Enter information about a cat: "<< endl;
cout << "NAME: ";
cin >> c[i].name;
cout << "AGE: ";
cin >> c[i].age;
wf.write((char *) &c[i], sizeof(Cat)); //writing struct object to binary file
i++;
}
cout<<"Record written to file"<<endl;
wf.close();
return 0;
}
OUTPUT:
Binary file: