I want to read the words of a file into a linked list. The file contains two words: cat & caterpillar.
However, the output of my linked list just spits out caterpillar twice. Something somewhere is wrong. Can someone please help.
------CODE-----
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char* word;
struct node* next;
}
node;
int main (int argc, char* argv[])
{
char *dictfile = argv[1];
FILE* dict = fopen(dictfile, "r"); //opens the file which contains two words, cat & caterpillar
if (dict == NULL)
return 1;
node* head = NULL;
char* oneword = malloc(sizeof(node));
while ((fgets (oneword, 24, dict)) != NULL)
{
node* temp = (node*)malloc(sizeof(node));
temp->word = oneword;
printf("%s\n", temp->word); //prints the word for debug sake
temp->next = head;
head = temp;
}
node* temp = (node*)malloc(sizeof(node));
temp = head;
while(temp != 0) //loop to print the linked list
{
printf("traverse %s\n", temp->word); /prefix'ing traverse to know its from linked list
temp = temp->next;
}
printf("SUCCESS!!\n");
}
When I run the program, this is what happens:
-----RESULT-----
./tempeol small checksmall
cat
caterpillar
traverse caterpillar
traverse caterpillar
SUCCESS!!