yulai
yulai

Reputation: 761

Using fgets() to read file line by line in C

So, I am working on getting my program to read a file line by line, storing each line (as a "string") into a linked list.

The following while-loop

FILE *f;
char string[longest];
while(fgets (string, longest, f) != NULL) {    //Reading the file, line by line
    printf("-%s", string);    //Printing out each line
    insert(file_list, string);  //Why does it not change?
}

The printf()-function works as expected, printing out each line. I put the hyphen as a test to see if it would separate between the lines. However, when inserting the "string" into a linked list, only the first string is inserted, multiple times.

For instance, let us say I have a text:

Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.

Now, when reading this file, and printing out the result, I get:

-Roses are red,
-Violets are blue,
-Sugar is sweet,
-And so are you.

However, when printing out the linked list, instead of getting the same result, I get:

Roses are red,
Roses are red,
Roses are red,
Roses are red,

Does anyone know why the "string" variable in the while-loop doesn't change after each iteration when inserting it into the linked list? It just inserts the first line four times.

What am I missing?

UPDATE: My insert code is as follows:

void insert(node_lin *head, char *dataEntry) {
    node_lin * current = head;

    if(current->data == NULL) {
        current->data= dataEntry;
        current->next = NULL;
    }

    else {
        while(current->next != NULL) {
            current = current->next;
        }

        current->next = malloc(sizeof(node_lin));
        current->next->data = dataEntry;
        current->next->next = NULL;
    }
}

Upvotes: 0

Views: 9076

Answers (1)

Nikhil Vidhani
Nikhil Vidhani

Reputation: 729

Insert code isn't correct. need to malloc() first and do strcpy of string into node's data. Here you're just copying the pointer.

void insert(node_lin *head, char *dataEntry) {
    node_lin * current = malloc(sizeof(node_lin));
    node_lin *p = NULL;

    /*make sure that an empty list has head = NULL */
    if(head == NULL) { /*insert at head*/
        strcpy(current->data, dataEntry);
        current->next = NULL;
        head = current;
    } else {
        p = head;
        while(p->next != NULL) {
            p = p->next;
        }
        /*insert at tail*/
        p->next = current;
        strcpy(current->data, dataEntry);
        current->next = NULL;
    }  
}

Upvotes: 1

Related Questions