I'm new to C programming and so I'm having some problems with a simple program I'm trying to code. Essentially I'm trying to read in a text file, store the individual words into a linked list, then display the list (actually, the real goal is to only store each unique word and how many times that word is found, but I'll get to that later...).
What I've attempted to do is read in each individual character from the file and check if it's alphabetic. If it is, I add the char into a character array until a full word is built. Once a non-alpha character is read, I add the character array to the linked list and reset the array, ready to start reading in the next word.
The problem I've encountered is when displaying the contents of the list, only the first 8 characters are displayed correctly - the ninth character is always a 'ŕ' and the tenth is a star character. e.g 'disconnect' is displayed as 'disconneá☼'. All words up to 8 characters in length display OK.
I'm sure my code is full of errors/inefficiencies so if anyone could tell me the areas I'm going wrong it would be greatly appreciated.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void BuildWord(char c, int i)
{
char word[50];
if ((c == 0) && (i != 0))
{
word[i] = '\0';
AddToList(word);
}
else
word[i] = c;
}
int AddToList(char word[])
{
typedef struct wordListT
{
int entries;
char words[50];
struct wordListT *next;
}
wordList;
wordList *head = NULL;
wordList *current = NULL;
if (head==NULL)
{
head = (wordList *) malloc(sizeof(wordList));
head->next = NULL;
current = head;
}
else
{
current->next = (wordList *) malloc(sizeof(wordList));
current = current->next;
current->next = NULL;
}
strcpy(current->words, word);
//current = head;
while (current != NULL)
{
printf("%s ", ¤t->words);
current = current->next;
}
}
int main(void)
{
char c;
int i, j = 0;
FILE *src = fopen("test.txt", "rt");
for (i = 0; !feof(src); ++i)
{
c = fgetc(src);
if (isalpha(c))
{
tolower(c);
BuildWord(c,j);
j++;
}
else
{
BuildWord(0,j);
j = 0;
}
}
fclose(src);
return 0;
}