the code works well except it will not count the last word in the file. I noticed the last word doesn't have a line feed at the end. How can I fix this?
Thanks!
flight
Code:
include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
//local declarations
char file_name[100] ;
int count ;
int update_counter = 0;
FILE *inp1, *out1 ;
// init some stuff
count=0 ;
// prompt the user
printf("Enter Filename : ") ;
// read the keyboard input
fgets(file_name, sizeof(file_name), stdin);
//remove the newline character from the end of the input filename
file_name[strlen(file_name) - 1] = '\0' ;
// open input file
inp1 = fopen(file_name, "r") ;
if(inp1 == NULL)
{
fprintf(stderr, "can't open %s\n", file_name) ;
exit(EXIT_FAILURE) ;
}
// open output file
out1 = fopen("output.txt", "w") ;
if(out1 == NULL)
{
fprintf(stderr, "can't open %s\n", "output.txt") ;
exit(EXIT_FAILURE) ;
}
// count the words in the input file
for ( ;; )
{
int ch = fgetc(inp1);
if ( ch == EOF )
{
break;
}
if ( isalpha(ch) || isdigit(ch) || ispunct(ch))
{
update_counter = 1;
}
if ( isspace(ch) && update_counter )
{
count++;
update_counter = 0;
}
}
//echo the word count for the file
printf("\nFile %s contains %d words \n\n", file_name, count) ;
//write the word count to the output file
fprintf(out1,"File %s contains %d words \n", file_name, count) ;
// we're done...close files
fclose(inp1) ;
fclose(out1) ;
return 0;