簡體   English   中英

C程序未讀取用戶名和密碼的.txt文件

[英]C program not reading .txt file for username and password

對於我的代碼,我需要制作一個.txt文件,其中包含用戶名(名字)和密碼(姓氏)。 我的代碼需要讀取該文件。 如果我輸入了正確的用戶名和密碼,它將使我登錄。如果不正確,它將無法使我登錄。到目前為止,在我的name.txt文件(包含用戶名和密碼的文件)中,

勒布朗·詹姆斯
喬·史密斯
尼克·戴維斯(Nick Davis)

如果我的用戶名和密碼正確,我希望它允許我登錄。 在運行代碼時,我遇到了嚴重錯誤。 我似乎在我的代碼算法中找不到問題。

//This is my code: 
#include <stdio.h>
#include <stdlib.h>

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("names.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;
}

您無需事先知道行數。 只需使用fscanf()讀取一對名稱和密碼,直到它返回EOF

while (fscanf(fp, "%s %s", accounts[j].id, accounts[j].password) != EOF) {
    ++j;
}

另外,不要使用feof() 它通常無法按您期望的方式工作。 feof()僅在程序嘗試讀取文件並失敗后才返回true值。 也就是說,它不會阻止您的循環嘗試讀取文件的末尾。

暫無
暫無

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

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