Write a C++ program that creates an output file, writes information to it, closes the file and open it again as an input file and read the information from the file

/*
Problem Statement :
Write a C++ program that creates an output file, writes information to it, closes the file and
open it again as an input file and read the information from the file.
*/

#include<iostream>
#include<fstream>
using namespace std;
class file
{
char name[50];
float price;
public: 
void accept()
{
    cout<<"\nEnter Book Name:";
cin>>name;
cout<<"\nEnter Price:";
cin>>price;
}
void display()
{
cout<<"\nBook Name: "<<name<<" Price: "<<price<<endl;
}
};
 
int main()
{
file o[10];
fstream f;
int i,n;
f.open("stu.txt",ios::out);
cout<<"How many records you want: ";
cin>>n;
for(i=0;i<n;i++)
{
o[i].accept();
f.write((char*)&o[i],sizeof(o[i]));
}
f.close();
f.open("stu.txt",ios::in);
for(i=0;i<n;i++)
{
f.read((char*)&o[i],sizeof(o[i]));
o[i].display();
}
f.close();
return 0;
}
/*
Output:
comp-sys-14@comp-sys-14:~$ cd Desktop
comp-sys-14@comp-sys-14:~/Desktop$ cd oop_final
comp-sys-14@comp-sys-14:~/Desktop/oop_final$ g++ file_1.cpp
comp-sys-14@comp-sys-14:~/Desktop/oop_final$ ./a.out
How many records you want: 2
 
Enter Book Name:cpp
 
Enter Price:200
 
Enter Book Name:java
 
Enter Price:400
 
Book Name: cpp Price: 200
 
Book Name: java Price: 400
comp-sys-14@comp-sys-14:~/Desktop/oop_final$ 
 
*/

Post a Comment

0 Comments