【发布时间】:2018-09-23 07:33:18
【问题描述】:
我正在尝试编写一个简单的用户名/密码验证系统。目前我的用户名可以正常工作并正确比较字符串,但我发现我的变量“密码”正在更改。假设用户名是“James”,密码是“123456”,用户名工作正常并且比较正确,但密码正确传递给方法,但是在while (fscanf(file, "%s %s\n", file_username, file_password) > 0) 行上,“password”变量突然更改为“James”,并且然后将其与文件变量 file_password 进行比较。
bool authenticate_login(char *username, char *password)
{
printf("\nMade it to authentication_login\n");
FILE *file;
char *file_username;
char *file_password;
bool match;
printf("\n%s\n", username);
printf("\nThe password is coming in as: %s\n", password);
if ((file = fopen("Authentication.txt", "r")) == NULL) {
perror("fopen");
return false;
}
while (fgetc(file) != '\n'); /* Move past the column titles in the file. */
/* Each line in the file contains the username and password separated by a white space. */
while (fscanf(file, "%s %s\n", file_username, file_password) > 0) {
printf("\n TESTING THIS LINE: %s", password);
/* Check if the username matches one in the file, and if the password matches for that username. */
printf("\n\n%s",file_username);
printf("\n%d",strcmp(file_username, username));
printf("\n\n%s",file_password);
printf("\n%s", password);
printf("\n%d",strcmp(file_password, password));
if (strcmp(file_username, username) == 0 && strcmp(file_password, password) == 0) {
match = true;
break;
}
}
fclose(file);
return match;
}
【问题讨论】:
-
未定义行为,因为您没有为
file_password和file_username分配内存。