C Program: Count Vowels in a File
Here, we will be counting the number of vowels (a, e, i, o , u) in a file.
We consider the same text file from our previous C program.
The file was tyger.txt
, which consists of the first stanza of "The Tyger" poem by William Blake.
Tyger Tyger, burning bright,
In the forests of the night;
What immortal hand or eye,
Could frame thy fearful symmetry?
The program too is similar to the previous C program, just that we declare one extra unsigned short int
variable to count the number of vowels. And inside the while
loop, the character read by the file pointer is checked for both lowercase and uppercase vowels.
#include <stdio.h>
int main() {
unsigned short vowels = 0;
char c, file[50];
FILE *fp;
printf("FILENAME: ");
scanf("%[^\n]", file);
fp = fopen(file, "r"); // 'r' opens the file in read mode
printf("READING THE CONTENTS OF THE FILE [ %s ]\n", file);
while((c = fgetc(fp)) != EOF) {
if(c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U') {
vowels++;
}
printf("%c", c);
}
printf("\n");
printf("NUMBER OF VOWELS: %hu \n", vowels);
fclose(fp);
return 0;
}
On running the program and entering tyger.txt
for the prompt to enter FILENAME
$ ./a.out
FILENAME: tyger.txt
we get