airdemko3
airdemko3

Reputation: 53

C program not reading .txt file for username and password

For my code I need to make a .txt file containing a username (first name) and a password (last name). My code needs to read that file. If I entered the correct user name and password it will log me in. If it is incorrect it not log me in. So far in my name.txt file (the file containing my usernames and passwords) I have

Lebron James
Joe Smith
Nick Davis

I want it to allow me to log in if my usernames and password are correct. As I run my code I get a breaking error. I can't seem to find the problem in my code algorithm.

//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;
}

Upvotes: 0

Views: 220

Answers (1)

giusti
giusti

Reputation: 3538

You don't need to know the number of lines in advance. Just read pairs of name and password with fscanf() until it returns EOF.

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

Also, don't use feof(). It usually doesn't work the way you expect. feof() only returns a true value after the program has attempted to read the file and failed. That is, it doesn't stop your loop from trying to read past the end of the file.

Upvotes: 1

Related Questions