0
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.

YanBir
  • 345
  • 4
  • 12
meksun
  • 41
  • 5
  • looks like you've got a typo - `feof(fp)` should be `!feof(fp)` as you want the loop to keep going whilst you've *not* reached the end of file – Chris Turner Mar 11 '20 at 14:19
  • 3
    [`for (... feof(fp) ...)` is always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). Don't check feof, check `fgetc` and `fgets` return value. – KamilCuk Mar 11 '20 at 14:21

1 Answers1

1

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

YanBir
  • 345
  • 4
  • 12