Variable-sized lines of text in linked list



I am trying to read a text file into memory without any knowledge of
how long each line will be. I am looking to store each line in a
linked list structure, however, I am unsure of how to dynamically
allocate space for each line.

This is how I set up the linked list...

typedef struct node {
char *line;
struct node *next;
} linkedlist;

linkedlist* createlinkedlist(void) {
linkedlist* head;
head = (linkedlist *)malloc(sizeof(linkedlist));
head->line = NULL;
head->next = NULL;
return head;
}

void addnode(linkedlist* list, char *line) {
linkedlist* freespot;
linkedlist* newnode;
freespot = list;
while (freespot->next != NULL)
freespot = freespot->next;
newnode = (linkedlist *)malloc(sizeof(linkedlist));
newnode->line = line;
newnode->next = NULL;
freespot->next = newnode;
}

So with this in place, how can I read in variable length lines,
malloc() the proper storage for each and pass the pointer to
addnode()?

Thanks!

Cheers,
Scott Nelson
.



Relevant Pages

  • Re: linked lists
    ... >> why do you have a pointer to a pointer to a node p?? ... > Because I need to modify the original pointer 'head'. ... struct node *next; ... struct node *newnode; ...
    (comp.lang.c)
  • Re: Variable-sized lines of text in linked list
    ... typedef struct node { ... linkedlist* head; ... linkedlist* freespot; ... newnode = malloc); ...
    (comp.lang.c)
  • LinkedList Pointer (REPOST - diff version)
    ... struct node * next; ... No problem until you are dealing with a pointer variable. ... void Push(struct node** headRef, int newData); ... Given an int and a reference to the head pointer (i.e. a struct ...
    (comp.lang.c)
  • LinkedList Pointer (REPOST - diff version)
    ... struct node * next; ... No problem until you are dealing with a pointer variable. ... void Push(struct node** headRef, int newData); ... Given an int and a reference to the head pointer (i.e. a struct ...
    (comp.lang.c)
  • Re: branch prediction optimization
    ... If you had a loop like ... head = NULL; ... although the first time through the loop will suffer. ... struct node *next; ...
    (comp.unix.programmer)