I have written a program that reads in words from a file "carol.txt" and stores them in a linked list, keeping a count of how many times each word occurs.
When i try to run the program i get a segmentation fault. After some investigation I think it may have something to do with fopen in main().
I don't have a debugger, so I'd be really grateful if someone could take a look at the code.
Here it is, sorry it's so long!
Code:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
typedef struct L
{
char *word;
int count;
struct L *next;
} list;
list *makenode(char *a, list *t)
{
list *h = calloc(1, sizeof(list));
h->word = a;
h -> count = 1;
h -> next = t;
return h;
}
/* strcmp didn't work so i had to create function comparestr*/
int comparestr (char *one, char *two)
{
int i;
for (i=0; i<50; i++)
{
if (one[i] == two[i])
{
return 0;
}
}
return 1;
}
/* shows if word already exists in the list */
list *findword(char *a, list *b)
{
while (1)
{
if (b->next==NULL)
{
return b;
}
else if (comparestr(a, b->next->word)==0)
{
(b->next->count)++;
return NULL;
}
else
{
return (findword(a, b->next));
}
}
}
char *readword(FILE *file)
{
int n;
char *word;
word = calloc(50, sizeof(char));
word[0] = tolower(fgetc(file));
while (islower(word[0])||word[0]==EOF)
{
word[0] = tolower(fgetc(file));
}
if (word[0]==EOF)
{
return NULL;
}
n=1;
word[1] = tolower(fgetc(file));
while ((islower(word[n])||word[n]==39||word[n]==44||word[n]==96) && n<49)
{
n++;
word[n]=tolower(fgetc(file));
}
while (!(islower(word[n])))
{
word[n] = 0;
n--;
}
n++;
word[n]='\0';
return word;
}
list *makelist(FILE *file)
{
char *word;
list *start= makenode(NULL, NULL);
list *temp=NULL;
while (1)
{
word = readword(file);
if (word == NULL)
{
return start;
}
temp=findword(word, start);
if (temp !=NULL)
{
temp->next = makenode(word, NULL);
}
if (temp==NULL)
{
free(word);
}
}
}
list *search (char *a, list *b)
{
while (1)
{
if (b->next==NULL)
{
return NULL;
}
else if (comparestr(a, b->next->word)==0)
{
return b->next;
}
else
{
return (search(a, b->next));
}
}
}
void results(list *h, char *ve)
{
if (h == NULL)
{
printf("WORD NOT FOUND \n");
return;
}
printf(" %s occurs %d times\n", ve, h->count);
}
void query (list *li)
{
char *nu;
printf("type the word you would like to search for \n");
nu = readword(stdin);
results(search(nu, li), nu);
}
void close(list *ha)
{
list *g;
list *j;
g = ha;
while (g->next !=NULL)
{
j=g->next;
free(g->word);
free(g);
g=j;
}
free(g->word);
free(g);
}
int main()
{
list *start;
FILE *file;
char array[15];
file = fopen( "carol.txt" , "r" );
start = makelist(file);
while (1)
{
printf("do you want to make a query?\n");
fgets(array, 15, stdin);
if (tolower(array[0])=='y')
{
query(start);
}
if (tolower(array[0])=='n')
{
fclose(file);
close(start);
return 0;
}
if (tolower(array[0])!='y')
{
printf("you have entered an incorrect answer please try again\n");
}
}
}
thanks a lot.