![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Jan 2006
Location: UK
Posts: 242
Rep Power: 3
![]() |
Classes in fstream
Hi just a quick question. I have a class called person, of which I would like to save to a file. I was wondering if I could save it to a file as I would a struct:
fin.read((char *)(&newPerson), sizeof(Person)); and to load it again: fout.write((char *)(&newPerson), sizeof(Person)); Have tried a couple of times but can't seem to get it to work. Is it actually possible? I really dont want to save attributes of each object on a seperate line if possible. Cheers in advance. Seif. |
|
|
|
|
|
#2 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
In C++ a class and a struct are essentially the same thing. The difference is default exposure (public, private, etc.). The problem with saving them to disk is that they might not look like what you think they look like. Compilers tend to align members on "even" boundaries, with the result that there are unused areas of padding. "Even" boundaries depend on the underlying architecture of the machine. Most compilers allow you to tell them not to do this. The saving is bytes, the cost is performance. Even if you get it right it might not work portably. It's what serialization is all about.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#3 |
|
Hobbyist Programmer
Join Date: Jan 2006
Location: UK
Posts: 242
Rep Power: 3
![]() |
Thanks DaWei, I've done a read of object serialization and found exactly what I needed. I knew the similarities of structs and classes but weren't sure if i was possible, and believe it or not my lecturer didn't know either when i asked him
thank god for the PFO! |
|
|
|
|
|
#4 | |
|
Programming Guru
![]() Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5
![]() |
Quote:
__________________
"Employ your time in improving yourself by other men's writings, so that you shall gain easily what others have labored hard for." -- Socrates |
|
|
|
|
|
|
#5 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Don't get me started
.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|