Enigma
Enigma

Reputation: 393

Cannot Correctly Scan File for LinkedList

I need help figuring out how to properly scan a file of text to put information into a linked list. The file is:

12   JackSprat   2     1    65000

13   HumptyDumpty  5   3    30000

17   BoPeep  2       3      30000

20   BoyBlue    3    2      58000

0

0 Is the indicator as to when the file has ended. Whenever I run my code, it loops 5 times, but only saves the first line. When I print the information of the linked list it just prints the first line 5 times. I need to read the whole file and then stop at 0 but I'm pretty stumped. Here is my code.

struct employeeData* initializeList(struct employeeData *head, FILE *ifp ){
struct employeeData *temptr;
struct employeeData *newnode;

printf("testin\n");

    while(!feof(ifp))
    {
        newnode = (struct employeeData*)malloc(sizeof(struct employeeData));

        if (head == NULL)
        {
            head = newnode;
            head->next = NULL;
        }
        else
        {
            temptr = head;
            while(temptr->next != NULL)
            {
                temptr = temptr->next;
            }
            temptr->next = newnode;

        }
        fscanf(ifp, "%d%s%d%d%lf", &newnode->EMP_ID, &newnode->name, &newnode->dept, &newnode->rank, &newnode->salary);
    }

return head;}

What is really weird is if I delete printf("testin\n"); the code then crashes at the cmd prompt.

Upvotes: 0

Views: 155

Answers (1)

Ivan Ivanovich
Ivan Ivanovich

Reputation: 946

newnode = (struct employeeData*)malloc(sizeof(struct employeeData)); add string: newnode->next = NULL;

or use calloc

if head != NULL then return unchanged head, this is exactly what you wanted?

Upvotes: 1

Related Questions