I'm having trouble reading in values to a linked list using fscanf in a loop.
The program ultimately compiles and runs, but the print function is not producing any output which leads me to believe that my linked list is not actually being created in my read function.
I set up a few error checking printf statements and discovered that my student *head value is NULL when it is returned back to main and then sent to the print function.
My functions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Student{
char* first;
char* last;
int i;
int j;
struct Student* next;
}student;
int main(int argc, char* argv[])
{
student *start = NULL;
char *studentInput = argv[1];
start = buildStudentList(studentInput,start);
printStudents(start);
free_students(start);
return 0;
}
student* buildList(char* studentsFile, student* head)
{
student *current = head;
char *f = malloc(sizeof(char) * 25);
char *l = malloc(sizeof(char) * 25);
int prior,level = 0;
FILE *in = fopen(studentsFile, "r");
if(in == NULL)
{
printf("\nThe input file failed to open\n");
return NULL;
}
else
{
while(!feof(in))
{
fscanf(in, "%s %s %d %d",f,l,&prior,&level);
student *new = (student*)malloc(sizeof(student));
new->first = (char*)malloc(sizeof(char) * 25);
new->last = (char*)malloc(sizeof(char) * 25);
current = new;
strcpy(current->first,f);
strcpy(current->last,l);
current->i = prior;
current->j = level;
current->next = NULL;
current = current->next;
}
free(first);
free(last);
fclose(in);
return head;
}
}
void print(student* head)
{
if(head == NULL)
{
printf("head is null");
return;
}
student *current = head;
while(current->next != NULL)
{
printf("\n\nFirst Name: %s\nLast Name: %s\nPriority: %d\nReading Level: %d\n\n", current->first, current->last, current->i, current->j);
current = current->next;
printf("makes to loop");
}
}
void free_students(student *head)
{
if(head == NULL)
{
return;
}
student *current = head;
while(current->next != NULL)
{
student *temp = current;
current = current->next;
free(temp->first);
free(temp->last);
free(temp);
}
free(current->first);
free(current->last);
free(current);
}
At this point the output is "head is null".