I have been doing a small project as part of my lab assignments and I encountered this funny probelm while working with the files in C++.
I have this class Member which I am using to store the member details.
class Member
{
private:
char name[30];
long int userid;
char depart[30];
int fine;
struct date doj;
char password[8];
public:
Member()
{
strcpy(name,"");
userid=0;
strcpy(depart,"");
fine=0;
struct date d;
getdate(&doj);
strcpy(password,"");
}
long int ret_userid();
char *ret_pass();
void getdata();
void display();
};
In this class I am taking the system date and storing it in a date structure as the date of joining.Now here is my getdata function & display function..
void Member::getdata()
{
cout<<"\Enter the name of the member :";
gets(name);
cout<<"Enter the user-id of the member :";
cin>>userid;
cout<<"Enter the name of the department to which the member belongs to :";
gets(depart);
char *str;
str=getpassword();
int len=strlen(str);
str[len]='\0';
for(int i=0;i<len;i++)
password[i]=str[i];
password[i]='\0';
}
void Member::display()
{
cout<<"\n\nMember Record :=>";
cout<<"\nName of the member :"<<name;
cout<<"\nUser-id :"<<userid;
cout<<"\nDate of joining:"<<doj.da_year<<"/"<<doj.da_mon<<"/"<<doj.da_day;
cout<<"\nDepartment :"<<depart;
cout<<"\nCurrent payable fine :"<<fine;
}
I am creating an object and call this getdata function and write this to a file.When I am reading it back to some other object from the file and displaying it everything is working fine except date.I am getting year correctly but the day and month are having some garbage value.Here is the code snippet I am using for writing to the file..
Member m;
m.getdata();
ofstream fout;
fout.open("member.dat",ios::binary|ios::app);
fout.write((char *)(&m),sizeof(m));
fout.close();
Reading is similar.
I thought of many reasons and the only one I can think of was maybe the getdate function gets the system date and copies that into the *doj.And from my small experience I have always had problems with files whenever any kinda dynamic allocation came into picture.I am really bugged and stuck at this point.Please,please help me out asap.Thanks in advance.