This has been discussed ad nauseam; feof
doesn't tell you if the file is going to finish at the next read, but if a read has been tried and failed due to end of file.
In your case, a solution can be to check if the read failed (by checking the return value of fscanf
), and in that case to deallocate the structure; this also makes your code more robust, since it checks also for errors others than EOF (e.g. IO errors, invalid data format, ...).
Incidentally, p = p->next
won't do what you expect. If you are building a linked list "on the fly", you could do something like this:
// Allocate the space for the first element
struct PlayerTime *head=malloc(sizeof(*head));
// p will always point to a pointer to the element to be filled;
// let's start with the head
struct PlayerTime **p=&head;
// Try to read
while(fscanf(f, "%f %s", &((*p)->seconds), (*p)->name)==2)
{
// If we are here, the last read was successful
// Move p to the pointer to the next element
p = &((*p)->next);
// ... and allocate the space for such element
*p = malloc(sizeof(**p));
}
// After exit, there's an extra element that we allocated but we couldn't read
// Free it
free(*p);
// And put the relevant pointer to NULL
// (it will terminate the list, or set head to NULL if no element has been read)
*p=NULL;