Spyros Mouchlianitis
Spyros Mouchlianitis

Reputation: 125

Read a file line by line to struct

I want to read a file which looks like this:

Spyros 1
George 2
John 3

and I want to store each student in a struct:

typedef struct studentR *student;
struct studentR{
   char name[MAXSTRING];
   int id;
   student next;
};

I have written the following piece of code which does what I want but only for the first line. How can I move it to the next line?

while(fscanf(fp, "%s %d", st->name, &st->id) != EOF){
    l = list_push_back(l, st->name, st->id);
}

Here is list_push_back

//enters the new student in the end of the list
list list_push_back(list l, char *name, int id){
    student new_student = (student)malloc(sizeof(struct studentR));
    assert(new_student);

    strcpy(new_student->name, name);
    new_student->id = id;
    new_student->next = NULL;
    
    //push payload(stsudent data) at the top if the list is empty
    if (list_isempty(l))
    {
        l->head = new_student;
        l->tail = new_student->next;
        l->size++;
    }else{
        //push the payload(student data) at the bottom if the list is NOT empty
        student last = (student)malloc(sizeof(struct studentR));
        assert(last); 
        last->next = new_student;
        l->tail = new_student;
        l->size++;
    }

    return l;
}

Upvotes: 0

Views: 48

Answers (1)

WhozCraig
WhozCraig

Reputation: 66244

Among the things wrong with that code:

  • Never properly set tail in the add-to-empty-list case.
  • Leak memory in the add-to-not-empty-list case (twice).
  • Sort-of-add a node in the add-to-not-empty-list case, but leak memory while doing it.

That function should look like this:

list list_push_back(list l, const char *name, int id)
{
    student new_student = malloc(sizeof *new_student);
    assert(new_student);

    strcpy(new_student->name, name);
    new_student->id = id;
    new_student->next = NULL;

    if (l->size == 0)
    {
        l->head = new_student;
    }
    else
    {
        l->tail->next = new_student;
    }
    l->tail = new_student;
    l->size++;

    return l;
}

That's all.

Upvotes: 1

Related Questions