473,387 Members | 1,520 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,387 software developers and data experts.

Help: OOP file I/O with C-strings

Hey there...
I hope someone can help me with my problem.
I want to write a class object with both strings and integers, to a file,
and be able to read it properly again. I thought that the code below worked
(because it appears as so in a c++ book), but it does not. Can you make it
work? =)

thanx

Code:
--------
#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
3 2169

"Andreas Palsgård" <12*****@get2net.dk(fjern 123)> wrote in message news:3f***********************@dread11.news.tele.d k...
I thought that the code below worked
(because it appears as so in a c++ book), but it does not.


You need to burn that C++ book . What you wrote will not work.
The most likely place you are running afoul is you just can't write
out a class containing a std::string (or just about any other non-trivial
object) by casting it to char* and calling write on it. The string
class frequently doesn't contain the data, just a pointer to it.

You're going to have to format the output yourself.
Jul 19 '05 #2
On Thu, 9 Oct 2003 20:06:44 +0200, "Andreas Palsgård"
<12*****@get2net.dk(fjern 123)> wrote:
Hey there...
I hope someone can help me with my problem.
I want to write a class object with both strings and integers, to a file,
and be able to read it properly again. I thought that the code below worked
(because it appears as so in a c++ book), but it does not. Can you make it
work? =)


You have to write each field out explicitly, and don't use
reinterpret_cast on class types.

See http://www.parashift.com/c++-faq-lit...alization.html

Tom
Jul 19 '05 #3


"Andreas Palsgård" wrote:
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));


That's a bad idea. A really bad idea.
If your book relly suggest doing this: throw it away, the
author doesn't know what he is talking about.

Disclaimer: The above may work. But for making it work the class
must fullfill certain properties. Your's doesn't.

Well: The solution is not to try to read and write a class as a whole
as the above attempts. Instead you give the class some read/write
functions which do the file reading/writing on a member base. Note
this may also mean to call read/write functions of the members, if there
are any or to create a way to safely read/write by this member function
itself:
class person
{
....
void writeTo( ofstream& out_file )
{
int len;

// age can be written directly
out_file.write( &age, sizeof( age ) );

// but not so string. since std::string has no
// binary write facility, we have to invent our own
// first write the length of the string, followed by
// the characters.

len = name.length();
out_file.write( len, sizeof( len ) );
out_file.write( name.c_str(), len );

len = colour.length();
out_file.write( len, sizeof( len ) );
out_file.write( colour.c_str(), len );
}

void ReadFrom( ifstream& in_file )
{
// age can be read directly
in_file.read( &age, sizeof( age ) );

// but not so the strings. But we know
// how they are stored. So start with
// reading the length
int len;
char* tmp;

in_file.read( &len, sizeof( len ) );

// then allocate enough storage to store what
// needs to be read
tmp = new char[ len + 1 ];
in_file.read( tmp, len );
tmp[len] = '\0'; // make sure it is a valid C-style string

name = tmp;

delete [] tmp;

// same for the other string

in_file.read( &len, sizeof( len ) );
tmp = new char[ len + 1 ];
in_file.read( tmp, len );
tmp[len] = '\0';
colour = tmp;
delete [] tmp;
}
Of course some helper functions would be great, which eg
do the mechanics of writing a string in binary to a stream.
But thats left as an exercise for the reader.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #4

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

Similar topics

1
by: dave | last post by:
I first started using HCW.exe to compile .rtf filew created with MS Word a couple of weeks ago. I used the file | new menu then selected New project in the dialog box and everything worked as...
21
by: Dave | last post by:
After following Microsofts admonition to reformat my system before doing a final compilation of my app I got many warnings/errors upon compiling an rtf file created in word. I used the Help...
2
by: fabien | last post by:
Hi, I am writing a POV-RAY editor with Python using either QT or GTK as GUI 'wrapper'. ( I am still trying both ) * * * * PYGTK * * * * I have downloaded PygtkScintilla-1.99.5. There is a...
6
by: wukexin | last post by:
Help me, good men. I find mang books that introduce bit "mang header files",they talk too bit,in fact it is my too fool, I don't learn it, I have do a test program, but I have no correct doing...
4
by: dixie | last post by:
Help, I'm really out of my depth here (not unusual I hear you say :-). I have just installed HTML Help in an application. I told it in the Project Properties the path to the help file. I then...
1
by: Tim Marshall | last post by:
I'm putting together my first help file (using Easy Help, http://www.easyhelp.com/). So far, so good. I'm able to use the Help File and Help Context ID to have things from my help file pop up...
22
by: KitKat | last post by:
I need to get this to go to each folders: Cam 1, Cam 2, Cam 4, Cam 6, Cam 7, and Cam 8. Well it does that but it also needs to change the file name to the same folder where the file is being...
3
by: lord.zoltar | last post by:
I've managed to get a nice little chm help system written. Now I need to display it! I added a HelpProvider to my MDIParent form and set the namespace of the HelpProvider to be the help file. So...
22
by: Amali | last post by:
I'm newdie in c programming. this is my first project in programming. I have to write a program for a airline reservation. this is what i have done yet. but when it runs it shows the number of...
6
by: priyajohal | last post by:
#include<fstream.h> #include<process.h> #include<stdlib.h> #include<conio.h> #include<string.h> #include<dos.h> #include<ctype.h> #include<stdio.h> void setup() void help();
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: 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: 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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.