C语言中写一个文本里存放的账号和密码和内存里的比较的代码完善一下代码typedef struct char usernameMAX_LENGTH; char passwordMAX_LENGTH; Account; FILE file1 = fopenidtxt r; if file1 == NULL printf无法打开文件!n;
首先,给出的代码中的结构体定义有问题,应该是:
typedef struct {
char username[MAX_LENGTH];
char password[MAX_LENGTH];
} Account;
另外,代码中的变量accountInfo没有定义,应该是一个Account类型的变量。同时,还需要一个整型变量count来保存账号的数量。
然后,代码中的文件操作有错误,应该使用file1和file2来读取账号和密码信息。最后,关闭文件应该使用fclose(file1)和fclose(file2)。
修改后的代码如下:
#include <stdio.h>
#define MAX_LENGTH 100
typedef struct {
char username[MAX_LENGTH];
char password[MAX_LENGTH];
} Account;
int main() {
FILE *file1 = fopen("id.txt", "r");
if (file1 == NULL) {
printf("无法打开文件!\n");
return 1;
}
Account accountInfo;
fscanf(file1, "%s", accountInfo.username);
fclose(file1);
FILE *file2 = fopen("password.txt", "r");
if (file2 == NULL) {
printf("无法打开文件!\n");
return 1;
}
fscanf(file2, "%s", accountInfo.password);
fclose(file2);
int count = 0;
FILE *file = fopen("accounts.txt", "r");
if (file == NULL) {
printf("无法打开文件!\n");
return 1;
}
while (fscanf(file, "%s %s", accounts[count].username, accounts[count].password) == 2) {
count++;
}
fclose(file);
// 比较账号和密码
for (int i = 0; i < count; i++) {
if (strcmp(accountInfo.username, accounts[i].username) == 0 && strcmp(accountInfo.password, accounts[i].password) == 0) {
printf("账号密码匹配!\n");
break;
}
}
return 0;
}
注意,这里假设accounts.txt文件中的账号和密码是以空格分隔的,每行表示一个账号和密码。strcmp函数用于比较字符串是否相等,需要包含头文件<string.h>
原文地址: https://www.cveoy.top/t/topic/iNcl 著作权归作者所有。请勿转载和采集!