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.