我有一个学校项目,要求我创建一个包含密码保护的C程序。我有一个功能处理登录,但是当输入错误的密码时,该功能仍然允许用户继续进入程序的主要部分。我尝试使用abort并退出,但他们没有帮助。看起来他们只是退出函数而不是程序。
这是我的代码。
void userlogin(void){
FILE *fp;
char uName[10], pwd[10];int i;char c;
pUser=(struct user *)malloc(sizeof(struct user));
printf("1. Login Through An Existing Account\n2. Create New account\n");
scanf("%d",& i);
//system("cls");
switch(i){
case 1:
if ( ( fp=fopen("user.dat", "r+")) == NULL) {
if ( ( fp=fopen("user.dat", "w+")) == NULL) {
printf ("Could not open file\n");
exit ( 1);
}
}
printf("Username: ");
scanf("%9s",uName);
printf("Password: ");
scanf("%9s",pwd);
while ( fread (pUser, sizeof(struct user), 1, fp) == 1) {
if( strcmp ( pUser->username, uName) == 0) {
printf ("Match username\n");
if( strcmp ( pUser->password, pwd) == 0) {
printf ("Match password\n");
//accessUser();
}
else if ( strcmp ( pUser->username, uName) == 1){
printf("INCORRECT PASSWORD\n");
printf("ACCESS DENIED");
abort();
}
}
}
break;
case 2:
do
{
if ( ( fp=fopen("user.dat", "a+")) == NULL) {
if ( ( fp=fopen("user.dat", "w+")) == NULL) {
printf ("Could not open file\n");
exit ( 1);
}
}
printf("Choose A Username: ");
scanf("%9s",pUser->username);
printf("Choose A Password: ");
scanf("%9s",pUser->password);
fwrite (pUser, sizeof(struct user), 1, fp);
printf("Add another account? (Y/N): ");
scanf(" %c",&c);//skip leading whitespace
}while(c=='Y'||c=='y');
break;
}
printf("Welcome %s\n", uName);
free ( pUser);//free allocated memory
fclose(fp);
}