C program to count from a file
Count the numbers of characters, vowels, consonant, lines, words, punctuation marks from a existing file.
Code
/*Write a program that will read the contains of a file and count the characters, vowels, consonant, lines, words, punctuation marks */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char fname[30],ch;
int c=0,v=0,ln=0,w=0,p=0;
//Taking a file name from the user
printf("\nEnter a file name to read: ");
gets(fname);
//Open the file in read mode
fp=fopen(fname,"r");
//Check is the file exist or not
if(fp==NULL)
{
printf("\nFile cannot be access.");
exit(0);
}
//Print the content of the file
printf("\nThe contain of the file is: \n");
while((ch=getc(fp))!=EOF)
{
printf("%c",ch);
//Checking and count the outputs
if((ch>=65&&ch<=90)||(ch>=97&&ch<=122))
{
c=c+1;
}
if((ch=='a')||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u')||(ch=='A')||(ch=='E')||(ch=='I')||(ch=='O')||(ch=='U'))
{
v=v+1;
}
if((ch=='.')||(ch=='?')||(ch=='!'))
{
ln=ln+1;
w=w+1;
}
if(ch==' ')
{
w=w+1;
}
if((ch==';')||(ch=='"')||(ch==','))
{
p=p+1;
}
}
//Print the outputs
printf("\nNumber of character in the file is %d",c); //Count the characters
printf("\nNumbers of vowels in the file is %d",v); //Count the vowels
printf("\nNumbers of consonant in the file is %d",(c-v)); //Count the consonants
printf("\nNumbers of lines in the file is %d",ln); //Count the lines
printf("\nNumbers of words in the file is %d",w); //Count the words
printf("\nNumbers of punctuation marks in the file is %d",p); //Count the punctuation marks
fclose(fp);
return 0;
}
Output
Enter a file name to read: temp.txt The containt of the file is: This is a temporary file. Number of charecter in the file is 20 Numbers of vouls in the file is 8 Numbers of consonent in the file is 12 Numbers of lines in the file is 1 Numbers of words in the file is 5 Numbers of punchuation marks in the file is 0