I have a program that's designed to read in words and split them apart, separating each and counting them up individually (words with punctuation differences are counted as different words on purpose).
typedef struct word
{
char letters[100];
int count;
} Word;
int compare (const void *a, const void *b)
{
return strcmp((*(struct word **) a)->letters,(*(struct word **) b)->letters);
}
int main()
{
int sizeCheck = 0;
Word ** collection = malloc(sizeof(Word*));
Word * array = malloc(sizeof(Word));
FILE *fptr, *fout;
char fileName[80];
char fileNameWords[80];
char wordLine[100];
strcpy(fileName,"data");
strcpy(fileNameWords,fileName);
strcat(fileNameWords,"data.out.txt");
Where the action starts, assuming everything's fine with opening files (removed for shortness sake):
int wordExists = 0;
int t1 = 0;
char tw1[100];
fscanf(fptr,"%s",wordLine);
strcpy(array->letters,wordLine);
array->count = 1;
collection[sizeCheck] = array;
sizeCheck++;
while (!feof(fptr))
{
wordExists = 0;
fscanf(fptr,"%s",wordLine);
for (t1 = 0; (t1 < sizeCheck) && (wordExists == 0); t1++)
{
strcpy(tw1,array[t1].letters);
if (strcmp(tw1,wordLine) == 0)
{
array[t1].count += 1;
wordExists = 1;
}
}
if (!wordExists)
{
collection = realloc(collection,(sizeCheck+1)*sizeof(Word*));
array = realloc(array,(sizeCheck+1)*sizeof(Word));
strcpy(array[sizeCheck].letters,wordLine);
array[sizeCheck].count = 1;
collection[sizeCheck] = array;
sizeCheck++;
}
}
qsort(collection,sizeCheck,sizeof(Word*),compare);
for (t1 = 0; t1 < sizeCheck; t1++)
{
fprintf(fout,"%s - %d\n",array[t1].letters,array[t1].count);
}
free(collection);
}
}
fclose(fptr);
fclose(fout);
return 0;
}
Using a pointer-to-pointer method, it works for the most part, except when it comes to either the qsort function, or the fprintf parts near the bottom. I'm a little stumped at this point. What am I doing wrong here that's preventing this from outputting a sorted file? (Sorting by alphabetical order with words)