write to & read from file ..something wrong!!

December 1, 2010 at 21:03:13
Specs: Macintosh
i wrote simple program to write objects to a file and its work, but i made another one to search for a specific object the user enter its number, find it and show it, but some letters from the output missed, any body has an idea about wat is going on plz ?

///////////////// the program to write objects///////////////

#include <iostream.h>
#include <fstream.h>

class pers {
private:
char name[40];
int age;
public:
void set_data() {
cout << " name : ";
cin >> name;
cout << "\n age : ";
cin >> age;
}
void show_data() {
cout << "\n name : " << name;
cout << "\n age : " << age;
}
};
///////////////////////////////////////

int main (int argc, char * const argv[]) {
char ch;
pers person;
fstream file;

file.open("pers_data.DAT", ios::in | ios::out | ios::binary | ios::app);

do {
cout << "\nEnter Persom Info---- " << endl;
person.set_data();
file.write( (char*)&person, sizeof(person) );
cout << "\nDo you like to add another person (y/n) : ";
cin >> ch;
}while (ch =='y');

file.seekg(0);

file.read( (char*)&person, sizeof(person) );

while ( ! file.eof() ) {
cout << "\nPerson Infor----";
person.show_data();
file.read((char*)&person, sizeof(person));
}

return 0;
}


//////////////// the program to read an object////////////////
#include <iostream.h>
#include <fstream.h>

class person {
protected:
int age;
char name[40];
public:
void dis_data(void) {
cout << "name is " << name;
cout << "\nage is : " << age;
}
};

int main (int argc, char * const argv[]) {
person pers;
ifstream ifile;
ifile.open("pers_data.DAT", ios::binary);
ifile.seekg(0, ios::end); // first we make it to pointer to the end.
int end_pos = ifile.tellg(); // after that we find the end possition.
int num = end_pos / sizeof(person); // then we find how many person we have.

cout << "\nwe have in this file " << num << " person!!!" << endl;

cout << "Enter number of person you want to search for : ";
cin >> num;
int position = (num-1) * sizeof(person);
ifile.seekg(position);

ifile.read( (char*) &pers, sizeof(pers) );
pers.dis_data();

return 0;
}

thank you......


See More: write to & read from file ..something wrong!!

Report •


#1
December 2, 2010 at 09:02:48
class pers {
private:
char name[40];
int age;

class person {
protected:
int age;
char name[40];

The order of your variables is relevant.

How To Ask Questions The Smart Way


Report •

#2
December 2, 2010 at 20:00:11
oooww thank you i noticed that but i didn't think will affect on the result, t was surprising ,
thanks.

Report •

Related Solutions


Ask Question