Re: [CODE] fread()ing problems.

From: Sean Daley (sdaley@bbnplanet.com)
Date: 02/26/99


Ok, it looks like there are a few problems here.  Let's take a look at
them.

On Sat, 27 Feb 1999, Andrew Ritchie wrote:
> However, I have run into another difficulty. I want to load an account
> structure from a binary file into memory, and into a linked list of all
> accounts. However, when it does not read any data if you like. It does put
> it in the linked list, but the information in the structure is blank. I'm
> positive my writing to the file in binary mode was all ok... here's the code:
>
> void load_account(char *filename)
> {
>    FILE *account;
>    struct account_data temp, *new;
>    int size;
>
>    new = calloc(1, sizeof(struct account_data));

Here you're setting aside space for the new account I assume.
Unfortunately this is the last time you use new.

>    sprintf(buf, "../lib/accounts/");
>    sprintf(buf + strlen(buf), filename);
>
>    if( (account = fopen(buf, "rb")) == NULL) {
>       log("Cannot open account file: '%s'", buf);
>       return;
>    }
>
>    fseek(account, 0L, SEEK_END);

Here you're moving to the end of the file.

>    size = ftell(account);

Grabbing the byte count.

>    if(size) {
>      if(size != sizeof(struct account_data)) {
>         log("File: '%s' corrupt.", buf);
>         return;
>      }
>      fread(&temp, sizeof(struct account_data), 1, account);

Now here you're calling fread on a file that is already at its end.  When
you called fseek and ftell earlier, you never rewound the file.  So
nothing is left to be stored in &temp.

>      temp.next = account_index;
>      account_index = &temp;

Now here is another problem.  Even if you had rewound the file, you're
trying to add a temporary structure to the account_index linked list (at
least I'm assuming it's a LL).  This is a "bad" thing.  You probably want
to utilize that *new you have up at the top.

>    }
>    else {
>      log("Empty account file: '%s'", buf);
>      return;
>    }
>
>    return;
> }

Hope this helps.

Sean


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     |  http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html  |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST