簡體   English   中英

從c中的文件讀取名稱和密碼

[英]read name and password from a file in c

我正在嘗試將文件中的名稱和密碼讀入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;
}

並且name_pass.txt文件是一個像這樣的簡單文件(name + password):

你好1234

哈哈123

世界123

您正在讀取文件兩次。 因此在第二個循環開始之前您需要fseek()或rewind()到第一個字符。

嘗試:

fseek(fp, 0, SEEK_SET); // same as rewind()   

要么

rewind(fp);             // s   

您需要在兩個循環之間添加此代碼(在第一個循環之后和第二個循環之前)

另外,您要為account struct id, password filed分配內存:

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

或按照@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;
}   

其工作方式如下:

:~$ cat name_pass.txt 
hello 1234

lol 123

world 123
:~$ ./a.out 
hello, 1234, lol, 123

您需要malloc()結構體中指針的內容,或者使用靜態大小對其進行聲明:

struct account {
    char id[20]; 
    char password[20];
};

您可能應該首先為要scanf的內容分配內存。關鍵字是malloc ,太長了,無法在此處進行講授。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM