I cannot seem to figure out how to get this to work. I need a few suggestions/help because the program keeps crashing and it does not insert the strings into the linked list properly.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct listNode
{
char *data;
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void insert(LISTNODEPTR *, char *);
void printList(LISTNODEPTR);
int main()
{
LISTNODEPTR root = NULL;
FILE *fptr;
char file_name[20];
char str[1000];
int numOfChar;
char *token;
int count = 0;
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)
{
token = fscanf(fptr, "%s", str);
while (token != NULL)
{
insert(&root, token);
token = fscanf(fptr, "%s", str);
}
}
fclose(fptr);
printList(root);
return 0;
}
void insert(LISTNODEPTR *sPtr, char *value)
{
LISTNODEPTR newPtr, previousPtr, currentPtr;
char *str;
newPtr = malloc(sizeof(LISTNODE));
str= (char *)malloc(60*sizeof(char));
strcpy(str, value);
if (newPtr != NULL) {/* is space available */
newPtr->data = str;
newPtr->nextPtr = NULL;
previousPtr = NULL;
currentPtr = *sPtr;
if (previousPtr == NULL) {
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else {
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
printf("%s not inserted. No memory available.\n", value);
}
void printList(LISTNODEPTR currentPtr)
{
if (currentPtr == NULL)
printf("List is empty.\n\n");
else {
while (currentPtr != NULL) {
printf("%s -->", currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
printf("NULL\n\n");
}
}