std::stream problem in data file handling

#include<fstream.h>
#include<conio.h>
#include<string>

class CLS
{
public : string name;
}c;

void main()
{
fstream f;
f.open("D:\\Text.txt", ios::out);

cin>>c.name;
cout<<"\n\nEntered Name: "<<c.name;
cout<<"\nSize : "<<c.name.size();
f.write((char*)&c, sizeof(CLS));
f.close();
getch();
}


I have used the above code to write the class instance to a file "Text.txt"... But it seems that "f.write((char*)&c, sizeof(CLS));" is not working properly with string. The data can easily be written using stream object!! Please someone tell me what's the problem and how can I correct it 'coz I require this type of codes for my Project also!!


#include<fstream.h>
#include<conio.h>
#include<string>

class CLS
{
public : string name;
}c;

void main()
{ string name;
fstream f;
f.open("D:\\Text.txt", ios::in);
f.read((char*)&c, sizeof(CLS));
cout<<"Name: "<<c.name.c_str();
cout<<"\nSize: "<<c.name.size();
f.close();
getch();
}

When I tried to read the data on the file...., it gave an error "Thread stopped...violation.."
Last edited on
Topic archived. No new replies allowed.