【发布时间】:2018-07-14 03:04:09
【问题描述】:
所以我正在尝试使用 struct 和 txt 文件来构建登录表单,我使用了一个注册函数,将用户名和密码保存到 txt 文件,并使用另一个函数通过读取和比较用户输入的值来登录部分.
但是代码似乎只比较了用户名和密码的第一行!其余的只提供错误的凭据,我如何让它比较其余的?
结构
struct user
{
char userID[10];
char username[50];
char password[50];
};
注册函数
char registration()
{
system("cls");
printf ("--------------------------------------------------------------------------------------\n");
printf("\t\t\t\tWelcome to Registration Page\n");
printf ("--------------------------------------------------------------------------------------\n\n");
date();
struct user person;
printf("Enter the UserID: ");
scanf(" %s", person.userID);
printf("\nEnter the username: ");
scanf(" %s", person.username);
printf("\nEnter the password: ");
scanf(" %s", person.password);
printf("This person has username %s and password %s\n", person.username, person.password);
FILE *outfile;
// open file for writing
outfile = fopen ("user.txt", "a");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
// write struct to file
fwrite (&person, sizeof(struct user), 1, outfile);
fclose(outfile);
if(fwrite != 0)
printf("\ncontents to file written successfully !\n");
else
printf("error writing file !\n");
return 0;
}
登录功能:
int login()
{
//system("cls");
printf ("--------------------------------------------------------------------------------------\n");
printf("\t\t\t\tWelcome to Login Page\n");
printf ("--------------------------------------------------------------------------------------\n\n");
date();
char username[50];
char password[50];
FILE *infile;
struct user person;
printf("\nPlease Enter your Username, Password to Proceed\n\n");
printf("\n\nUsername: ");
scanf(" %s", &username);
printf("\nPassword: ");
scanf(" %s", &password);
infile = fopen ("user.txt", "r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
// read file contents till end of file
while(fread(&person, sizeof(struct user), 1, infile)){
if(strcmp(username,person.username) == 0 && \
strcmp(password, person.password) ==0)
{
hrmenu();
break;
}
else
{
printf("Wrong Credentials, Please try again!\n");
login();
}
}
fclose(infile);
return 0;
}
【问题讨论】:
-
你为什么在
login()打开两次infile? (顺便说一句,使用perror进行错误报告,它知道为什么文件没有打开。) -
注意
"%s"前加一个空格是没有效果的。 -
以纯文本形式存储密码从根本上说是不安全的。虽然这可能只是一个编程练习,但它是一个坏习惯。 "Secure Salted Password Hashing" 是开始阅读存储密码的好地方。
-
@DYZ 我的错,已编辑
-
@Schwern 不,只是一些有文字要求的作业,但感谢您提供的信息