You are guaranteed that the max length of a word is 30, meaning char word[31];
would suffice for each word:
#define WORDSIZE 31
#define WORDLEN_FMT "%30s" //width must be WORDSIZE-1!
/* Read a space-delimited word from `fileptr` and store it in `word`.
*
* Returns:
* 0 - maybe more words to read
* 1 - no more words to read
* -1 - error occurred while reading input
*/
int get_word(FILE *fileptr, char word[WORDSIZE]) {
size_t i;
switch (fscanf(fileptr, WORDLEN_FMT, word)) {
// EOF or an error was encountered.
case EOF:
if (ferror(fileptr)) {
return -1;
}
/* Fallthrough for `feof() != 0`. */
// If nothing was stored in `word`, then we're done.
case 0:
return 1;
}
// A word was stored, so keep going!
return 0;
}
As for reading all words, you could either allocate 1000 words initially, or you could deal with dynamic allocation and grow the array capacity by some factor x
as necessary; I'd personally pre-allocate the 1000 words since I know there will never be more than 1000. Whichever you choose, it'll be important to keep track of the length of the array of words since it's unlikely that you'll use every bit of the memory you allocate (i.e. array_length < array_capacity
usually.) I'll leave this up to you.
Finally, you can sort words easily with qsort
and a wrapper around strcmp
:
// Compare the words pointed to by `a` and `b`.
int compare_words(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
...
// Sort `word_array` using the `compare_words` function.
// The array contains `word_count` words, each with size `WORDSIZE`.
qsort(word_array, word_count, WORDSIZE, compare_words);