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