Click to See Complete Forum and Search --> : serialization
August 19th, 1999, 11:12 AM
Hi,
I would like to write some objects to disk using MFC serialization. What I need though is to to write
in text form, not binary. I was thinking of using ofstream but dont know exactly how to go about doing%0
Thanks
replika
August 19th, 1999, 01:44 PM
fstream.h is part of the C++ runtime library
You can use fstream like this:
In the header file:
#include <fstream.h>
class Person
{
private
char m_strName[256];
public:
Person(char *);
friend ifstream &operator>>(ifstream &, Person &);
friend ofstream &operator<<(ofstream &, const Person &);
};
In the source file:
ifstream &operator>>(ifstream &ifs, Person &per)
{
ifs.getline(per.m_strName, 256);
return ifs;
}
ofstream &operator<<(ofstream &, const Person &per)
{
ofs << m_strName << endl;
return ofs;
}
This enables you to write code like:
Person a("replika"), b;
ofstream out("DATAFILE.DAT");
out << a;
out.close();
ifstream in("DATAFILE.DAT");
in >> b;
in.close();
This is pretty basic knowledge. Found in any book by Herb Schildt.
mikeMiller
August 19th, 1999, 03:42 PM
Thanks for replying replika,
Actually, I don't think that I was clear enough with my question. Assume that I want to serialize a set of
classes. When the overriden Serialize function of the document gets called, I want to call the Serialize
functions of my own classes but I want to write in text form. Some thing like
void CTestDoc::Serialize(CArchive& ar)
{
// get the list of objects and call serialize
for (...)
obj->Serialize(ar);
}
// the problem is, the CFile object attached to ar is in binary mode. If I could somehow change it so that
I could write in text form that would be great. I tried this
void CTestDoc::Serialize(CArchive& ar)
{
CString str = " something";
ofstream out(ar.GetFile()->GetFileName());
out<<str<<endl;
// this didnt work either.
}
// I think that once you open the file in a particular mode you cant change it.
// I also tried closing the file and opening it again in text mode but that didnt work either.
// I am really frustrated with this. If you can give me hand I would really appreciate it.
Thanks
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.