首先,需要定义AccountInfo结构体,以及count变量来存储读取的账号和密码数量。

typedef struct {
    char account[100];
    char password[100];
} AccountInfo;

int count = 0;
AccountInfo accounts[MAX_ACCOUNTS];

接下来,需要在循环中读取文件中的账号和密码,并与内存中的账号和密码进行比较。

FILE *file = fopen("accounts.txt", "r");
if (file == NULL) {
    printf("无法打开文件!\n");
    return 1;
}

for (int i = 0; i < count; i++) {
    fscanf(file, "%s %s", accounts[i].account, accounts[i].password);
    if (strcmp(accounts[i].account, accountInfo.account) == 0 && strcmp(accounts[i].password, accountInfo.password) == 0) {
        printf("账号密码匹配!\n");
        break;
    }
}

fclose(file);

完整代码如下:

#include <stdio.h>
#include <string.h>

#define MAX_ACCOUNTS 100

typedef struct {
    char account[100];
    char password[100];
} AccountInfo;

int main() {
    AccountInfo accountInfo;

    FILE *file1 = fopen("id.txt", "r");
    if (file1 == NULL) {
        printf("无法打开文件!\n");
        return 1;
    }
    fscanf(file1, "%s", accountInfo.account);
    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;
    AccountInfo accounts[MAX_ACCOUNTS];
    FILE *file = fopen("accounts.txt", "r");
    if (file == NULL) {
        printf("无法打开文件!\n");
        return 1;
    }

    for (int i = 0; i < count; i++) {
        fscanf(file, "%s %s", accounts[i].account, accounts[i].password);
        if (strcmp(accounts[i].account, accountInfo.account) == 0 && strcmp(accounts[i].password, accountInfo.password) == 0) {
            printf("账号密码匹配!\n");
            break;
        }
    }

    fclose(file);

    return 0;
}

注意,这里假设id.txt和password.txt文件中只有一个账号和密码,如果有多个账号和密码需要适当修改代码。另外,需要提前定义MAX_ACCOUNTS来限制账号和密码的数量

C语言中写一个文本里存放的账号和密码和内存里的比较的代码完善一下代码AccountInfo accountInfo; 		FILE file1 = fopenidtxt r; 		if file1 == NULL 		 		printf无法打开文件!n; 		return 1; 	 		fscanffile1 s accountInfoaccount

原文地址: https://www.cveoy.top/t/topic/iNcd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录