Write a program to carry out the following:
To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text,
each line with a maximum of 80 characters.
Count and display the number of words contained in the file.
Display the total number of four letter words in the text file.
Assume that the end of a word may be a space, comma or a full-stop followed by one
or more spaces or a newline character.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char word[80];
int numberWords=0;
int numberFourLetterWords=0;
FILE *ptrFile;
if ((ptrFile = fopen("TRIAL.txt", "r")) == NULL) {
printf("Error! File cannot be opened.");
exit(1);
}
while (fscanf(ptrFile,"%s",word)!= EOF) {
numberWords++;
if(strlen(word)==4){
numberFourLetterWords++;
}
}
printf("The number of words contained in the file: %d\n",numberWords);
printf("The total number of four letter words in the text file: %d\n",numberFourLetterWords);
getchar();
getchar();
return 0;
}
Comments
Leave a comment