Reputation: 41
void
loadUsers(user userList[])
{
int i, nUserAcc = 0;
char c, temp[20];
FILE *fp = fopen ("Users.txt", "r");
if (fp == NULL)
fp = fopen("Users.txt", "w");
for (nUserAcc = 0; nUserAcc < MAX_USERS && feof(fp); nUserAcc++) {
i = 0;
c = 0;
while (c != 32) {
c = fgetc(fp);
temp[i] = c;
i++;
}
temp[i] = '\0';
userList[nUserAcc].nID = atoi(temp);
fgets(userList[nUserAcc].aPassword, 12, fp);
userList[nUserAcc].aPassword[strlen(userList[nUserAcc].aPassword) - 1] = '\0';
fgets(userList[nUserAcc].aName, 22, fp);
userList[nUserAcc].aName[strlen(userList[nUserAcc].aName) - 1] = '\0';
fgets(userList[nUserAcc].aAddress, 32, fp);
userList[nUserAcc].aAddress[strlen(userList[nUserAcc].aAddress) - 1] = '\0';
fgets(temp, 20, fp);
userList[nUserAcc].nContact = atoi(temp);
}
fclose(fp);
}
So I have this code wherein it's supposed to be loading data from the User.txt file and storing it into structure arrays, but it's not and I don't know where I went wrong.
Upvotes: 0
Views: 56
Reputation: 375
As @KamilCuk said the using of feof() in this way can be always wrong. You should check if end of file is arrived while you read data:
while (fgets(..)) {...}
Now to your question:
It seems you used wrong feof() return value in your for. You wrote:
for (nUserAcc = 0; nUserAcc < MAX_USERS && feof(fp); nUserAcc++) {...}
But actually: feof() returns the value zero when end of the file has not occurred, otherwise it returns 1.
In other words the for loop is not occurred. Change to:
for (nUserAcc = 0; nUserAcc < MAX_USERS && !feof(fp); nUserAcc++) {...}
See an example here: https://www.includehelp.com/c-programs/feof-function-in-c-language-with-example.aspx
Upvotes: 1