While running this section, my .dat
file gets some random characters. I don't get it, what am I doing wrong?
fstream file("trial1.dat", ios::app | ios::in | ios::out);
file.seekg(0, ios::end);
login obj1; //Pre-loaded accounts
login obj2;
login obj3;
login obj4;
login obj5;
strcpy(obj1.password, "wr100m1234");
strcpy(obj1.userid, "creative");
strcpy(obj2.password, "pass123400");
strcpy(obj2.userid, "logitech");
strcpy(obj3.userid, "microsof");
strcpy(obj3.password, "coolermast");
strcpy(obj4.userid, "lenovo12");
strcpy(obj4.password, "surface103");
strcpy(obj5.userid, "hewlett1");
strcpy(obj5.password, "packard999");
cout << obj1.userid;
file.write((char *)&obj1, sizeof(obj1)); //writing all the userids and passwords to file
file.write((char *)&obj2, sizeof(obj2));
file.write((char *)&obj3, sizeof(obj3));
file.write((char *)&obj4, sizeof(obj4));
file.write((char *)&obj5, sizeof(obj5));
int z;
cout << "Do you want to use existing id or create new id?(1/2) \n";
cin >> z;
if(z == 2)
{
file.seekg(0, ios::end);
login a;
cout << "Enter id \n";
cin >> a.userid;
cout << "Enter pass \n";
cin >> a.password;
file.write((char *)&a, sizeof(a));
z = 1;
}
int l;
if(z == 1)
{
login a1, a2;
cout << "Enter id \n";
cin >> a1.userid;
cout << "Enter password \n";
cin >> a1.password;
while(!file.eof())
{
file.read((char *)&a2, sizeof(a2)); //reading of object from file
if(strcmp(a1.userid, a2.userid) == 0 && strcmp(a1.password, a2.password) == 0)
{
cout << "Login Successful \n";
l = 1;
break;
}
else
{
cout << "Login failed \n";
l = 0;
break;
}
}
}
file.close();
This is the code for the password checking. I wanted to have some pre-defined logins as well as to create new login ids. While executing this code, the trial1.dat
has some random characters.
login
is defined withchar userid[10]
andchar password[10]
.