C++/Problems with file handling in C++
Expert: Eddie - 1/24/2008
QuestionSir, I had written the following code in C++:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
class Student
{
int rollno;
char name[20];
char add[30];
public:
void enterdata(void);
void display(void);
};
void Student::enterdata(void)
{
cout<<"Enter Roll No. ";
cin>>rollno;
cout<<"Enter the name: ";
cin.getline(name, 20);
cout<<"Enter Address: ";
cin.getline(add, 30);
cout<<"\n";
}
void Student::display(void)
{
cout<<"ROLL NO. : "<<rollno<<"\t";
cout<<"NAME: "<<name<<"\t";
cout<<"ADDRESS"<<add<<"\t";
cout<<"\n";
}
int main()
{
clrscr();
Student s1[3];
fstream filin;
filin.open("stu.txt", ios::in|ios::out);
if(!filin)
{
cout<<"Cound not find file";
return 1;
}
cout<<"Enter records for 10 students\n";
for(int i=0;i<3;i++)
{
s1[i].enterdata();
filin.write((char*)& s1[i],sizeof(s1[i]));
}
for(i=0;i<3;i++)
{
filin.read((char*)& s1[i],sizeof(s1[i]));
s1[i].display();
}
filin.close();
return 0;
}
Now, watever values i enter some garbage gets stored in my text file which looks like:
198 7$ Lý&ý9Lý w ý2ýŸ#Lý Hý>ý%zý @
öÿ103198
can u help me..........is thr some other way for executing programs wid file handling in TURBOC++ in DOS mode??????????
AnswerHello vineet, thank you for the question.
The reason you are writing garbage to the file is because you are casting the address of your Student to a char*. You could try something like making your Student have a WriteFile method like this:
void Student::WriteFile(ofstream &o)
{
o << rollno << ' ' << name << ' ' << add << '\n';
}
This will write the actual class values out, which you can read back in. This should have you pointing in the right direction.
I hope this information was helpful.
- Eddie