I have researched a lot into isolating words within strings, storing the words and sorting them.
I have managed to isolate the words, and store them into a struct. But there is a problem within my algorithm as it is only storing the first word of the text file. So for example if the text file held "Hello there" Only the "Hello" is stored in position [0] of the struct, "there" is not stored in position [1] though?
Can somebody help?
CODE
#include <stdio.h>
#include <string.h>
typedef int boolean;
typedef struct word
{
char word[50];
}Word;
int main(int argc, char* argv[])
{
FILE* fname;
char list[1000];
boolean readw;
int Counter, i, j;
Word* words;
int num_words;
num_words = 0;
printf("\n\t\t\t""***Welcome To*** \n\t Conor's File Opening & Searching Program""\n\n\n\n");
printf("\n\n");
for (Counter = 1; Counter < argc; Counter++)
{
fname = fopen(("%s", argv[Counter]), "r");
if (fname == NULL)
{
printf("****Now opening %s...****\n\n", argv[Counter]);
printf("Sorry, the file '%s', could not be found/opened""\n\n", argv[Counter]);
}
else
{
printf("****Now opening %s...****\n\n", argv[Counter]);
printf("\n****File opened, now displaying contents...**** \n\n");
while(!feof(fname))
{
while (fgets(list, 100, fname)!= NULL)
{
if (num_words == 0)
{
words = calloc(1, sizeof(Word));
}
else
{
words = realloc(words, (num_words + 1)* sizeof(Word));
}
for(i = 0, j = 0; list[i] != ' '; i++, j++)
{
words[num_words].word[j] = list[i];
}
words[num_words].word[j] = '\0';
num_words++;
}
}
for (i = 0; i < num_words; i++)
{
printf("%s\n", words[i].word);
}
if (words != NULL)
{
free(words);
printf("%s's data has been removed from memory", argv[Counter]);
}
fclose(fname);
printf("\n\n****File now closed****\n\n");
}
}
return 0;
}