Hi all.
Why does the while loop in the main() function keep executing?
Thanks in advance.
Code:
// wordcount.c: count the number of occurrences of every word in a text file
// 4 functions: openfile, countwords, sort, display
#include <stdio.h>
#include <string.h>
#define FILENAMELENGTH 30
#define SUCCESS 1
#define FAILURE 0
FILE *fp;
int openfile(char *string);
int main(void)
{
int result;
char filename[FILENAMELENGTH];
printf("Enter file to open: ");
fgets(filename, FILENAMELENGTH, stdin);
filename[strlen(filename) + 1] = '\0';
while((result = openfile(filename)) == FAILURE)
{
printf("File could not be opened. Enter file to open: ");
fgets(filename, FILENAMELENGTH, stdin);
filename[strlen(filename) + 1] = '\0';
result = openfile(filename);
}
return 0;
}
int openfile(char *string)
{
if((fopen(string, "r")) == NULL)
return FAILURE;
else
{
printf("\n%s opened successfully", string);
return SUCCESS;
}
}