sdsd
sdsd

Reputation: 61

Creating a linked list from a text file

I'm teaching myself about linked lists and have proposed a basic problem to solve. I want to line by line read a text file that will have names and add each name to my linked list.

An example of the text file would be:

John
Jacob
Jingleheimer
Smith

I am having trouble figuring out how to dynamically add to my proposed linked list. Here is what I have so far.

#include <stdio.h>
#include <stdlib.h>



int main(void)
{
    struct node {
        char *name;
        struct node* next;
    };


    static const char* fileName = "test.txt";
    FILE *fp = fopen(fileName,"r");
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    struct node* head = NULL; // first node

    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1)
    {
        //add line of text to linked list
    }
    if (line)
        free(line);

       exit(EXIT_SUCCESS);

}

Any pointers into the right direction would be helpful.

Upvotes: 1

Views: 6601

Answers (2)

Gille
Gille

Reputation: 5773

Ok, to do this you need to first allocate a node entry, then copy the line you just read into it. Then add it to the list. (I've left out error handling, such as malloc returning NULL).

/* This will store the last read line first */
while ((read = getline(&line, &len, fp)) != -1)
{
    struct node *n = malloc(sizeof(*n));
    n->name = strdup(line); /* copy the line since it can get reused by getline */
    n->next = head;
    head = n;
}

Upvotes: 3

Avery3R
Avery3R

Reputation: 3190

Allocate memory to hold the string, set that memory = to the string. Then

node *next = malloc(sizeof(node));
next->name = name;
next->next = NULL;
head->next = next;
head = next;

Upvotes: 0

Related Questions