Thanks to Prelude, I've nearly got my program doing what it's meant to - just have one more annoying problem that I'm sure is down to my simple stupidity...
I am trying to add words from a textfile to a linked list, store only the unique words and count how many of each word appears. The problem I'm now having is with the counting - I can either get the program to add every word, or one word e.g. reading in a typical 1000 word essay, the first way stores all 1000 words (not just the unique ones), and the second way stores only the first word and counts it as having appeared 1000 times!
This is obviously down to my poor logical programming, so if someone could tell/show me where I'm going wrong then I can finally get some sleep!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct wordList
{
int entries;
char words[50];
struct wordList *next;
} wordList_t;
wordList_t *AddToList (wordList_t *head, char word[])
{
wordList_t *current = NULL;
wordList_t *ptr = head;
int found = 0;
while (ptr != NULL){
if (strcmp(ptr->words, word)){
ptr->entries++;
found = 1;
}
ptr = ptr->next;
}
if ((head != NULL) && (found == 0)){
current = malloc (sizeof *current->next);
current->next = head;
head = current;
strcpy (head->words, word);
head->entries = 1;
}
if (head == NULL) {
head = malloc (sizeof *head);
head->next = NULL;
strcpy (head->words, word);
head->entries = 1;
}
return head;
}
/*wordList_t search (wordList_t head, char word[])
{
wordList_t ptr;
ptr = head;
while (ptr != NULL && strcmp(word, ptr->words) != 0){
ptr = ptr->next;
}
return (ptr);
}*/
void PrintList (wordList_t *head)
{
FILE *newhtml = fopen("new.html", "w");
fprintf(newhtml,"<html><body>\n<ul>");
while (head != NULL){
fprintf(newhtml, "<li>%i - %s</li>", head->entries, head->words);
head = head->next;
}
fprintf(newhtml,"</ul></body></html>");
fclose(newhtml);
}
int main (int argc, char *argv[])
{
char c;
int i, j = 0;
char word[50];
FILE *src;
wordList_t *list = NULL;
if ((src = fopen (argv[1], "r")) == NULL)
printf("You did not specify a document or the document cannot be found!");
else {
for (i = 0; (c = fgetc(src)) != EOF; ++i){
if (isalpha(c))
word[j++] = tolower(c);
else if ((!isalpha(c)) && (j != 0)){
word[j++] = '\0';
list = AddToList (list, word);
j = 0;
}
}
PrintList(list);
fclose(src);
}
return 0;
}