473,378 Members | 1,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

HELP: Class object I/O

Hey.. i want to write a class object containing both strings and integers,
to a file on disk, and be able to read it properly again at another time. I
made the code below... it doesn't work, but what am i doing wrong.

thanx
Andy
-----------------------------------
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class person
{
protected:
string name,colour;
int age;
public:
void getdata()
{
cout << "Enter name:" ; cin >> name;
cout << "Enter Age:"; cin >> age;
cout << "Enter colour:"; cin >> colour;
}
void showdata()
{
cout << "Name: " << name << endl;
cout << "Age:" << age << endl;
cout << "Colour:" << colour << endl;
}
string get_name(){ return name;}
int get_age(){ return age;}
string get_colour(){ return colour;}
};

person tim;

void file_in(){
person temp_pers;
ifstream infile("person.dat", ios::in | ios::binary);
infile.read(reinterpret_cast<char*>(&temp_pers),si zeof(temp_pers));
infile.close();
tim = temp_pers;
cout << temp_pers.get_name() << endl;
cout << temp_pers.get_age() << endl;
cout << temp_pers.get_colour() << endl;
}
void file_out(){
tim.getdata();
person temp_pers;
temp_pers = tim;
ofstream outfile("person.dat", ios::binary | ios::out | ios::trunc);
outfile.write(reinterpret_cast<char*>(&temp_pers), sizeof(temp_pers));
outfile.close();
cout << temp_pers.get_name() << endl;
cout << temp_pers.get_age() << endl;
cout << temp_pers.get_colour() << endl;
}
/////////////////////////////
int main()
{
file_out();
//file_in();
return 0;
}
Jul 19 '05 #1
6 1735

"Andreas Palsgård" <12*****@get2net.dk(fjern 123)> wrote in message news:3f***********************@dread11.news.tele.d k...
Hey.. i want to write a class object containing both strings and integers,
to a file on disk, and be able to read it properly again at another time. I
made the code below... it doesn't work, but what am i doing wrong.

You posted this already. You can not write out most classes (other than
the most simple) by casting their pointer to char* and calling Write.
Your book, if it actually says to do that, is worse than useless. Burn it.
The problem is that classes (such as string) may contain pointers to
data elsewhere that is neither written by your hack nor properly restored
when read in. Further you may stomp on C++ overhead for things like
virtual functions that you have no business accessing.
Jul 19 '05 #2
Andreas Palsgård wrote:
Hey.. i want to write a class object containing both strings and integers,
to a file on disk, and be able to read it properly again at another time. I
made the code below... it doesn't work, but what am i doing wrong.

the problem is:
you don't know the size of the data you are writing to the file in advance.
You have to make any char * into a char[fixed_size]
to be able to let any size_of(your_object) return a descent value.
that way your reinterpret_cast<hex> won't fail....

so no char * pointers please...

Jul 19 '05 #3
Hi,

Object serialization is a great thing, unfortunately there is no magic
behind it. Do the following:

Define a function (possibly operator<< or serialize with in = false ) to
write every value of the class to disk.

Define a function ( possibly operator>> or serialize ( with in = true) to
read every value from disk.

For aggregated classes call the serialize member with the "in" or the
operator>> or operator<< parameter.

This will cause a tree of serialization to occur If every class knows how to
correctly write and read its values it will succeed.

In a few words, every object is responsible for reading or writing itself to
persistent storage.

Regards, Ron AF Greve.
"Andreas Palsgård" <12*****@get2net.dk(fjern 123)> wrote in message
news:3f***********************@dread11.news.tele.d k...
Hey.. i want to write a class object containing both strings and integers,
to a file on disk, and be able to read it properly again at another time. I made the code below... it doesn't work, but what am i doing wrong.

thanx
Andy
-----------------------------------
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

class person
{
protected:
string name,colour;
int age;
public:
void getdata()
{
cout << "Enter name:" ; cin >> name;
cout << "Enter Age:"; cin >> age;
cout << "Enter colour:"; cin >> colour;
}
void showdata()
{
cout << "Name: " << name << endl;
cout << "Age:" << age << endl;
cout << "Colour:" << colour << endl;
}
string get_name(){ return name;}
int get_age(){ return age;}
string get_colour(){ return colour;}
};

person tim;

void file_in(){
person temp_pers;
ifstream infile("person.dat", ios::in | ios::binary);
infile.read(reinterpret_cast<char*>(&temp_pers),si zeof(temp_pers));
infile.close();
tim = temp_pers;
cout << temp_pers.get_name() << endl;
cout << temp_pers.get_age() << endl;
cout << temp_pers.get_colour() << endl;
}
void file_out(){
tim.getdata();
person temp_pers;
temp_pers = tim;
ofstream outfile("person.dat", ios::binary | ios::out | ios::trunc);
outfile.write(reinterpret_cast<char*>(&temp_pers), sizeof(temp_pers));
outfile.close();
cout << temp_pers.get_name() << endl;
cout << temp_pers.get_age() << endl;
cout << temp_pers.get_colour() << endl;
}
/////////////////////////////
int main()
{
file_out();
//file_in();
return 0;
}

Jul 19 '05 #4
klaas wrote:
Andreas Palsgård wrote:
Hey.. i want to write a class object containing both strings and
integers,
to a file on disk, and be able to read it properly again at another
time. I
made the code below... it doesn't work, but what am i doing wrong.

the problem is:
you don't know the size of the data you are writing to the file in advance.
You have to make any char * into a char[fixed_size]
to be able to let any size_of(your_object) return a descent value.
that way your reinterpret_cast<hex> won't fail....

so no char * pointers please...

If you have the fixed size issue ready i can give you a wrapper class
that implement harddisk based arrays...
let me know

Jul 19 '05 #5
well... actually i found this out:
My little program deosn't work with strings... but if you convert strings to
char[] it works perfectly.
You can write the whole object to a file with reinterpret_cast[char*]...

Andreas

"Ron Natalie" <ro*@sensor.com> wrote in message
news:3f*********************@news.newshosting.com. ..

"Andreas Palsgård" <12*****@get2net.dk(fjern 123)> wrote in message news:3f***********************@dread11.news.tele.d k...
Hey.. i want to write a class object containing both strings and integers, to a file on disk, and be able to read it properly again at another time. I made the code below... it doesn't work, but what am i doing wrong.

You posted this already. You can not write out most classes (other than
the most simple) by casting their pointer to char* and calling Write.
Your book, if it actually says to do that, is worse than useless. Burn

it. The problem is that classes (such as string) may contain pointers to
data elsewhere that is neither written by your hack nor properly restored
when read in. Further you may stomp on C++ overhead for things like
virtual functions that you have no business accessing.

Jul 19 '05 #6
Andreas Palsgård wrote:
well... actually i found this out:
My little program deosn't work with strings... but if you convert strings to
char[] it works perfectly.
You can write the whole object to a file with reinterpret_cast[char*]...
You _can't _ use reinterpret_cast<> on a string. It is a complex class
and not a simple type. Use the string::c_str() method for conversion
to an array of characters (C-style string) and a constructor for
converting from a C-style string to a std::string.


Andreas


1. Don't Top-Post (replies are appended to the bottom, or interspersed
throughout).
2. Strings are known as variable record types when serializing.
(See also C++ faq about serializing).
You have to decide whether you want to use the
[quantity][text] or [text][sentinel]
layout.
3. Strings are one of those types that is best serialized in one
form, but used internally in another. Endianism is another
of these same issues.

In my Binary_Stream class, I have chose the [quantity][text]
layout. I also have every class write out their own members.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Tommy Lang | last post by:
I am working on this project and I need some help/pointers/comments to get me started, I am stuck. The program will be used to store information in an array while it is running. I need to store...
5
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I...
7
by: Alan Bashy | last post by:
Please, guys, In need help with this. It is due in the next week. Please, help me to implement the functions in this programm especially the first three constructor. I need them guys. Please, help...
4
by: Mike | last post by:
Please help this is driving me nuts. I have 2 forms, 1 user class and I am trying to implement a singleton class. Form 1 should create a user object and populate some properties in user. Form2...
3
by: Colin J. Williams | last post by:
Python advertises some basic service: C:\Python24>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> With...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
53
by: Hexman | last post by:
Hello All, I'd like your comments on the code below. The sub does exactly what I want it to do but I don't feel that it is solid as all. It seems like I'm using some VB6 code, .Net2003 code,...
0
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted...
5
by: althafexcel | last post by:
hi everyone Im trying to include an external js in my aspx page under the head tag, it doesn't load or it displays an object expected error whenver the function from the .js is called. Actually...
2
by: hcaptech | last post by:
This is my Test.can you help me ? 1.Which of the following statement about C# varialble is incorrect ? A.A variable is a computer memory location identified by a unique name B.A variable's name...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.