A problem with files in C++

[img]http://lengejoorab.persiangig.ir/c++problem.JPG[/img]
This is simple program. theres a class whit a string and an integer. it gets data as objects of this class and save s it in a file (left pic). I can view them correctly after this (middle pic). But if i close the program and then run it again i 'll see view the file incorrectly (right pic).


#include <iostream>
#include <conio>
#include <fstream>
#include <stdio>

class data
{
int n;
char *st;
public:
data();
void getdata();
void showdata();
};
//***********************
data::data()
{
st=new char[40];
}

void data::getdata()
{
cout<<"Enter n: ";
cin>>n;
cout<<"Enter string: ";
gets(st);
}

void data::showdata()
{
cout<<"n: "<<n<<endl;
puts(st);
}
//***********************
void enter();
void view();
//***********************
void main()
{
char ans;
while(1)
{
clrscr();
cout<<"1)New data\n2)View\n3)Exit";
ans=getch();
switch(ans)
{
case '1': enter(); break;
case '2': view(); break;
case '3':return;
}
}
}
//***********************
void enter()
{
clrscr();
data d;
ofstream ofile;
ofile.open("Data",ios::binary|ios::app);
d.getdata();
ofile.write((char*) &d,sizeof(data));
ofile.close();
}

void view()
{
clrscr();
data d;
ifstream ifile;
ifile.open("Data",ios::binary);
while(ifile.read((char*) &d,sizeof(data)))
{
d.showdata();
cout<<"\n\n";
}
getch();
}

This is your data class:
class data
{
int n;
char *st;
public:
data();
void getdata();
void showdata();
};


Here you write a data object:
data d;
...
ofile.write((char*) &d,sizeof(data));


What is sizeof(data)? The object has an int and a char* so the size is 8 for all data objects.

You need to write the actual data to the file and not the pointer.

Then you need to read the data into buffers and then create your data object and poprulate it with the bytes you read.

That means you will need a file layout or you can't read your file.

Lastly, why are you using char* in your data class instead of a string object? After all, this is C++ and not C.
thank you for your note
Topic archived. No new replies allowed.