This shows an easy but good way to handle it, for a small to medium sized password file, without using a linked list.
Linked lists are the classic way to handle an unknown number of input items, but they are time consuming to work with.
You have a file with 26 passwords: passwords.txt, in the same directory.
Code:
#include <stdio.h>
#include <stdlib.h> //for malloc()
#include <string.h> //for strlen()
int main(void) {
int i, len, passNum=0;
char passWord[30]={'\0'};
char **A;
FILE *fp=fopen("passwords.txt", "r");
if(!fp) {
printf("Error! Password file did not open\n");
return 0;
}
//count the number of passwords
while((fgets(passWord, 30, fp)) != NULL)
++passNum;
printf("There are %d passwords in the file\n",passNum);
rewind(fp); //move the file pointer, back to the beginning
//allocate the password array (2D)
A = malloc(passNum * sizeof(char*));
for(i=0;i<passNum;i++) {
A[i]=malloc(30); //each password can have 29 chars in it.
}
for(i=0;i<passNum;i++) {
fgets(A[i], 30, fp);
printf("%s",A[i]);
len=strlen(A[i])-1;
if(*A[len]=='\n') //if present, remove the newline
*A[len]='\0'; //from the end of the password
//strcmp() calls can work properly now
}
fclose(fp);
printf("\n\n");
return 0;
}
Contents I used for passwords.txt file:
alpha
beta
charlie
delta
echo
foxtrot
golf
hotel
India
Juliet
kilo
Lima
Mike
November
Oscar
Papa
Quebec
Romeo
Sierra
Tango
uniform
victor
whiskey
x-ray
yankee
zulu