I'm working on some homework and one of the functions I need to write should look through a text file that represents a dictionary and update a struct with the number of words I found, the shortest word, and the longest word.
However, when I try to run the program, it just hangs out in command prompt for a while as if I'm in a infinite loop.
int info(const char *dictionary, struct DICTIONARY_INFO *dinfo)
{
/* Variable Declarations */
FILE *fp; /* Pointer to the file being opened */
char str[21] = {0}; /* Char array to hold fgets */
unsigned int longest_length; /* Length of the longest word in the dict */
unsigned int shortest_length; /* Length of the shorest word in the dict */
int number_words; /* Number of words in dict */
longest_length = 0;
shortest_length = 21;
number_words = 0;
/* Opens the file */
fp = fopen(dictionary, "rt");
/* If the file was successfully opened */
if(fp)
{
/* While we're not at the end of the file */
while(!feof(fp))
{
/* If we can successfully get a line with fgets */
if(fgets(str, strlen(str), fp))
{
/* Replaces the NL char with a null 0. */
my_nl_replace(str);
/* If the length of this word is longer than our current longest */
if(strlen(str) > longest_length)
longest_length = strlen(str);
/* If the length of this word is shorter than the current shortest */
if(strlen(str) < shortest_length)
shortest_length = strlen(str);
++number_words;
}
}
/* Closes the file, since we're done using it */
fclose(fp);
/* Modifies the dictionary struct with the info just collected */
(*dinfo).shortest = shortest_length;
(*dinfo).longest = longest_length;
(*dinfo).count = number_words;
return FILE_OK;
}
/* If the file was not successfully opened */
else
{
return FILE_ERR_OPEN;
}
}
And if anyone's curious, the nl_reaplace thing is as follows:
void my_nl_replace(char *string)
{
string[(strlen(string))] = '\0';
}