I am trying to write a program that will extract each string(word) from a text file and insert it into a linked list. The problem is my program keeps crashing and I cannot figure out why. I believe it is my insert method but I am not sure. Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char *data;
struct node *next;
};
void insertNode(struct node**, char *);
void printList(struct node*);
int main()
{
struct node *head = NULL;
FILE *fptr;
char file_name[20];
char str[1000];
int numOfChar;
printf("Enter the name of the file: ");
scanf("%s",file_name);
printf("Enter the number of characters per line: ");
scanf("%d",&numOfChar);
fptr=fopen(file_name,"r");
while(fgets(str, sizeof str, fptr) != NULL)
{
int nitems = fscanf(fptr, "%999s", str);
while (nitems == 1)
{
insertNode(&head, str);
nitems = fscanf(fptr, "%999s", str);
}
}
fclose(fptr);
printList(head);
return 0;
}
void insertNode(struct node** nodeHead, char *data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
struct node *last = *nodeHead;
char *str;
str= (char *)malloc(60*sizeof(char));
strcpy(str, data);
new_node->data = str;
new_node->next = NULL;
if (*nodeHead == NULL)
{
*nodeHead = new_node;
return;
}
while (last->next != NULL)
{
last = last->next;
}
last->next = new_node;
}
void printList(struct node* node)
{
while(node != NULL)
{
printf(" %s ", node->data);
node = node->next;
}
}