-
Notifications
You must be signed in to change notification settings - Fork 0
/
file handing from object to file
115 lines (101 loc) · 2.03 KB
/
file handing from object to file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<fstream>
using namespace std;
class Book
{
private:
int bookid;
char title[20];
float price;
public:
void displayBook()
{
cout<<bookid<<" "<<title<<" "<<price<<endl;
}
void inputBook()
{
cout<<"Enter bookid, title and price: ";
cin>>bookid;
if(bookid<0)
bookid=-bookid;
cin.ignore();
cin.getline(title,20);
cin>>price;
}
void store();
void viewAllBooks();
};
void Book::store()
{
ofstream fout;
fout.open("bookfile.dat",ios::app|ios::binary);
fout.write((char*)this,sizeof(*this));
fout.close();
}
void Book::viewAllBooks()
{
ifstream fin;
fin.open("bookfile.dat",ios::in|ios::binary);
if(!fin)
cout<<"File Not Found";
else
{
fin.read((char*)this,sizeof(*this));
while(!fin.eof())
{
displayBook();
fin.read((char*)this,sizeof(*this));
}
}
fin.close();
}
int menu()
{
int choice;
cout<<"\n1. Store new Book Record";
cout<<"\n2. View All Book Records";
cout<<"\n3. Exit";
cout<<"\n\nEnter your choice";
cin>>choice;
return choice;
}
int main()
{
Book b1;
while(true)
{
switch(menu())
{
case 1:
b1.inputBook();
b1.store();
break;
case 2:
b1.viewAllBooks();
break;
case 3:
exit(0);
default:
cout<<"Invalid Choice";
}
}
}
Explaination snippet
class MyClass {
public:
int x;
};
int main() {
MyClass obj;
obj.x = 42;
// Casting the object pointer to a char pointer
char* charPtr = (char*)&obj;
// Now charPtr points to the same memory location as obj,
// but you can treat it as a sequence of bytes
for (int i = 0; i < sizeof(obj); ++i) {
std::cout << charPtr[i] << " ";
}
return 0;
}