Hi all. I'm a hopelessly stuck C newbie. I'm trying to make a program that will read one line at a time from a file, and store each line as a char array in a singly linked list. I'm now totally stumped by a segmentation fault. Any help would be greatly appreciated. The code is as follows:
Code:
#include <stdio.h>
struct listNode {
char data[20];
struct listNode *nextPtr;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
int main()
{
ListNodePtr *startPtr = NULL, newPtr, previousPtr, currentPtr;
FILE *fp;
fp=fopen("dictionary.dat","r");
if (fp!=NULL){
while(!feof(fp)){
newPtr = (ListNode *)malloc(sizeof(ListNode));
if (newPtr!=NULL){
fscanf(fp,"%s",newPtr->data);
newPtr->nextPtr = NULL;
printf("%s\n",newPtr->data);
previousPtr = NULL;
currentPtr = *startPtr;
while((currentPtr!=NULL)){
previousPtr = currentPtr;
currentPtr=currentPtr->nextPtr;
}
if (previousPtr == NULL){
*startPtr = newPtr;
}
else {
previousPtr->nextPtr = newPtr;
}
}
else{
printf("\nWarning: Not enough memory available to complete loading.\n\n");
break;
}
}
}
else{
printf("\n\n\tERROR: Dictionary file not found. Exiting.\n\n");
exit();
}
fclose (fp);
return 0;
}
I added the printf in the middle to try to help me figure out when it was going wrong. It displays the first word in the file but none of the others.
I figure when i've got the singly linked list working, it wont be so hard to update it to a doubly linked list... hopefully.
Thanks.