Nearly there with getting this program finished but I've run into another problem - my program keeps crashing after trying to implement a merge sort. It all compiles OK but crashes as soon as I run it.
I'm thinking the fault lies with my method of checking the words being added to the list - I'm reading in words from a text file, storing the unique ones in the list, and counting how many of them appear in the text. If I just read in every word (without counting etc), the program appears to work OK.
Anyway, here's my code - I would be extremely grateful if someone could highlight where I'm going wrong.
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 *MergeSort (wordList_t *head);
wordList_t *Merge (wordList_t *ptr1, wordList_t *ptr2);
wordList_t *talloc (void)
{
return (wordList_t *)malloc(sizeof(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) == 0){
ptr->entries++;
found = 1;
}
ptr = ptr->next;
}
if ((head != NULL) && (found == 0)){
current = talloc();
strcpy (current->words, word);
current->entries = 1;
current->next = head;
head = current;
}
if (head == NULL) {
head = talloc();
head->next = NULL;
strcpy (head->words, word);
head->entries = 1;
}
return head;
}
wordList_t *MergeSort (wordList_t *head)
{
wordList_t *ptr1, *ptr2;
if ((head == NULL) || (head->next == NULL))
return head;
ptr1 = head;
ptr2 = head->next;
while ((ptr2 != NULL) && (ptr2->next != NULL)){
head = head->next;
ptr2 = ptr2->next->next;
}
ptr2 = head->next;
head->next = NULL;
return Merge(MergeSort(ptr1), MergeSort(ptr2));
}
wordList_t *Merge (wordList_t *ptr1, wordList_t *ptr2)
{
wordList_t *ptr3;
if (ptr1 == NULL)
return ptr2;
if (ptr2 = NULL)
return ptr1;
if (ptr1->entries < ptr2->entries){
ptr3 = ptr1;
ptr3->next = Merge(ptr1->next, ptr2);
}
else{
ptr3 = ptr2;
ptr3->next = Merge(ptr1, ptr2->next);
}
return ptr3;
}
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;
}
}
fclose(src);
PrintList(MergeSort(list));
free(list);
}
return 0;
}