I am trying to read in a text file and add strings from it word by word into a Linked List. I'm fairly new at C and don't quite understand pointers. I've had a few different errors just messing around with it, but now I'm getting an infinite loop within my main program.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct listNode { /* self-referential structure */
char data[50];
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void insert(LISTNODEPTR *, char[]);
char delete(LISTNODEPTR *, char[]);
void printList(LISTNODEPTR);
int fpeek(FILE *);
main() {
FILE *fptr;
char file_name[20];
int nrchar = 0;
LISTNODEPTR startPtr = (struct listNode *) malloc(sizeof(struct listNode));
startPtr->nextPtr = NULL;
char word[50];
char c;
int i;
printf("What is the name of the file in which the text is stored?\n");
scanf("%s",file_name);
// printf("Type the number of characters per line");
//scanf("%d", &nrchar);
fptr = fopen(file_name,"r");
while(fpeek(fptr) != EOF) {
i = 0;
while(fpeek(fptr) != ' '){
word[i] = fgetc(fptr);
i++;
printf("%d",i);
}
word[i] = '\0';
insert(&startPtr, word);
printf("%c", word[4]);
}
fclose(fptr);
printList(startPtr);
return 0;
}
/* Insert a new value into the list in sorted order */
void insert(LISTNODEPTR *sPtr, char value[])
{
LISTNODEPTR newPtr, currentPtr;
newPtr = malloc(sizeof(LISTNODE));
strcpy(newPtr->data, value);
newPtr->nextPtr = NULL;
currentPtr = *sPtr;
while(currentPtr && currentPtr->nextPtr){
currentPtr = currentPtr->nextPtr;
}
currentPtr->nextPtr = newPtr;
}
/* Return 1 if the list is empty, 0 otherwise */
int isEmpty(LISTNODEPTR sPtr)
{
return sPtr == NULL;
}
/* Print the list */
void printList(LISTNODEPTR currentPtr)
{
if (currentPtr == NULL)
printf("List is empty.\n\n");
else {
printf("The list is:\n");
while (currentPtr != NULL) {
printf("%s --> ", currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
printf("EOF\n\n");
}
}
int fpeek(FILE *stream) {
int c;
c = fgetc(stream);
ungetc(c, stream);
return c;
}
When I run my full code, it prints 12345ooooooooooooooooooooooo...etc. In my test file the first word is "Hello" so that's where the infinite 'o's come from. If the outer loop is the one that is infinite, then wouldn't the second while loop also execute more than once? What I mean is, why is the second print statement the only one that repeats itself?