This pointer for file reading in C++

Status
Not open for further replies.

ashvarybabul

Inactive
Discoverer
Hii Guyz,

I am having trouble using this pointer inside the class for reading the data form the file...

Here is the small code as an example to explain the problem

Code:
#include<fstream.h>
#include<conio.h>

class emp
{
char ename[50];
int eno;

public:

void getdata();
void viewdata();
};

void emp::getdata()
{

cout<<endl<<"Enter name:";
cin>>ename;
cout<<endl<<"Enter registration no:";
cin>>eno;

fstream gd;
	gd.open("emp.txt",ios::out||ios::app);
gd.write((char*)this,sizeof(emp));

gd.close();

}
void emp::viewdata()
{
ifstream rd;
rd.open("emp.txt",ios::in);

while(!rd.eof())
	  {
rd.read((char*)this,sizeof(emp));
	cout<<"Employee Name is:"<<ename<<endl;
	cout<<"Employee number is:"<<eno<<endl;
	  }//while

rd.close();

}

void main()
{
int ch;
label:
emp e1;

cout<<"Enter choice:"<<endl;
cout<<endl<<"1)Add\n2)View";
cin>>ch;
cout<<endl;

if(ch==1)
{
e1.getdata();
cout<<endl<<endl;
goto label;
}

if(ch==2)
{
e1.viewdata();
cout<<endl<<endl;
goto label;
}

getch();
}

Here, class is used to read and write in file simple data of emp..

well the data easily writes in the file, without any problem..
but when data is read from file, in output it only shows the last data of emp..

Eg : Suppose I run the add function two times..
data entered..
Ename: Ash Eno: 2
Ename: Sum Eno: 11


Now when I want to display all data from file and run view function, it only show last data input .i.e. output is ..

Ename: Sum Eno: 11


What to do so that all data get displayed..??
plz HELP friends...
friday is my practical day for board, so better if I get the answer before it..:D
 
(looks like its already in append mode just fine.)

its probably that "this" does not point to start of "ename" or "eno" due to class vtable/struct packing/alignment issues based on compiler version/platform.

try using two statements in each method like:

Code:
gd.write((char*)ename,strlen(ename));

gd.write((char*)eno,sizeof(eno));

similarly for reading...
 
Status
Not open for further replies.