从c中的文件中读取名称和密码

Min*_*ing 1 c file

我试图从文件中读取名称和密码到c中的结构,但显然我的代码不能按预期工作.有没有人可以帮我解决下面附带代码的问题?非常感谢!(基本上该文件有几个名称和密码,我想将它们读入结构帐户[]`)

#include <stdio.h>
#include <stdlib.h>

struct account {
    char *id; 
    char *password;
};

static struct account accounts[10];

void read_file(struct account accounts[])
{
    FILE *fp;
    int i=0;   // count how many lines are in the file
    int c;
    fp=fopen("name_pass.txt", "r");
    while(!feof(fp)) {
        c=fgetc(fp);
        if(c=='\n')
            ++i;
    }
    int j=0;
    // read each line and put into accounts
    while(j!=i-1) {
        fscanf(fp, "%s %s", accounts[j].id, accounts[j].password);
        ++j;
    }
}

int main()
{
    read_file(accounts);
    // check if it works or not
    printf("%s, %s, %s, %s\n",
        accounts[0].id, accounts[0].password,
        accounts[1].id, accounts[1].password);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

和name_pass.txt文件是一个像这样的简单文件(名称+密码):

你好1234

大声笑123

世界123

Gri*_*han 5

你正在读两次文件.所以你需要在第二个循环开始之前将fseek()或rewind()转换为第一个char.

尝试:

fseek(fp, 0, SEEK_SET); // same as rewind()   
Run Code Online (Sandbox Code Playgroud)

要么

rewind(fp);             // s   
Run Code Online (Sandbox Code Playgroud)

这个代码需要在两个循环之间添加(在第一个循环之后和第二个循环之前)

另外,您要为id, password filedin 分配内存account struct:

struct account {
    char *id; 
    char *password;
};
Run Code Online (Sandbox Code Playgroud)

或者像@AdriánLópez在答案中建议的那样静态分配记忆.

编辑 我纠正了你的代码:

struct account {
    char id[20]; 
    char password[20];
};
static struct account accounts[10];
void read_file(struct account accounts[])
{
    FILE *fp;
    int i=0;   // count how many lines are in the file
    int c;
    fp=fopen("name_pass.txt", "r");
    while(!feof(fp)) {
        c=fgetc(fp);
        if(c=='\n')
            ++i;
    }
    int j=0;
    rewind(fp);  // Line I added
        // read each line and put into accounts
    while(j!=i-1) {
        fscanf(fp, "%s %s", accounts[j].id, accounts[j].password);
        ++j;
    }
}
int main()
{
    read_file(accounts);
    // check if it works or not
    printf("%s, %s, %s, %s\n",
        accounts[0].id, accounts[0].password,
        accounts[1].id, accounts[1].password);
    return 0;
}   
Run Code Online (Sandbox Code Playgroud)

其工作如下:

:~$ cat name_pass.txt 
hello 1234

lol 123

world 123
:~$ ./a.out 
hello, 1234, lol, 123
Run Code Online (Sandbox Code Playgroud)