0

I am working on a data structure project. I am asked to take information from a file called "ToServe.txt". The data in the file is in the form:

TicketNumberSpaceStudentIDSpaceStudentName
TicketNumberSpaceStudentIDSpaceStudentName

However, implementing the two functions below, I only get the last student infinite times in my queue

int Start(advisee** front, advisee** rear) {
  advisee* student, *walker;
  FILE* infp;
  student = (advisee*)malloc(sizeof(advisee));
  infp = fopen("ToServe.txt", "r");
  if(infp == NULL) {
    return 0;
  }
  while(!feof(infp)) {
    fscanf(infp, "%d", &student->ticket);
    fscanf(infp, "%d", &student->ID);
    fgets(student->name, 100, infp);
    student->next = NULL;
    enqueue(front, rear, student);
  }
  walker = *front;
  fclose(infp);
  return 1;
}
void enqueue(advisee** front, advisee** rear, advisee* ToAdd) {
    if (*front == NULL)
      *front = ToAdd;
    else
      (*rear)->next = ToAdd;
    *rear = ToAdd;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 1
    `while(!feof(infp)) {` <<-- who taught you that? https://stackoverflow.com/q/5431941/905902 – wildplasser Nov 30 '21 at 12:25
  • 1
    Does this answer your question? [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – wildplasser Nov 30 '21 at 12:27
  • @wildplasser The while condition is correct, or at least not the problem here. I tried printing the information directly instead of creating a queue and it worked. – Mohammad Harouak Nov 30 '21 at 12:28
  • 3
    As to the question: you only allocate space for *one* advisee, so why would you expect more than one? They are all the same. It couldn't be any different. You just keep modifying the properties of the same node. – trincot Nov 30 '21 at 12:29

1 Answers1

1

There is only one item allocated:

advisee* student = (advisee*)malloc(sizeof(advisee));

...and the loop just keeps mutating that single advisee and repeatedly adds the same pointer to the queue. So the queue ends up with pointers to one single advisee.

The solution is to move the allocation inside the loop.

trincot
  • 317,000
  • 35
  • 244
  • 286