The technique you're trying to accomplish in building your ordered linked list is called forward-chaining. And a pointer-to-pointer makes the task trivial. Error checking memory allocations not-withstanding, it is done something like this:
struct node *root = NULL, **pp = &root;
char buf[MAXBUF];
size_t size = 0;
while (fgets(buf, MAXBUF, f) != NULL)
{
*pp = malloc(sizeof(**pp));
strncpy((*pp)->data, buf, MAXBUF);
pp = &(*pp)->next;
++size;
}
*pp = NULL; // terminate the last node
How It Works
The only parts of this that require elaboration are the following:
struct node *root = NULL, **pp = &root
The above line declares the root pointer, initialized to NULL, and a pointer-to-pointer that holds the address of the root pointer. From there...
*pp = malloc(sizeof(**pp));
This allocates a new node, storing its address at whatever pointer is currently being addressed by the pointer-to-pointer pp
. On the initial pass that pointer is the root
pointer. It will change as the iterations move through the file, but it always holds the address of pointer that is to receive the next new node.
After the string copy, then this is done:
pp = &(*pp)->next;
This stores the address of the just-added-node's next
member in the pointer-to-pointer. When we loop around for the next iteration, this is where we will hang the next new node. Finally, after the loop finishes, this is done:
*pp = NULL;
This sets the pointer pointed-to by pp
to NULL. Now think about what pointer that is:
- If no items were populated in the list, then
pp
still holds the address of root
and this will reestablish root
as NULL; exactly what you want if the list is empty.
- If any nodes were read, then
pp
will hold the address of the last added-node's next
pointer, which should set to NULL to terminate the linked list. Again, exactly what this code does.
Thats it. Best of luck.
Addendum: Printing the list
Per request, printing the list after this is simply:
struct node *ptr = root;
while (ptr)
{
printf("data: %s\n", ptr->data);
ptr = ptr->next;
}
For C99 users,
for (struct node *ptr = root; ptr; ptr = ptr->next)
printf("data: %s\n", ptr->data);
Hope it helps