Write a program in ANSI C that counts the number of times th
Write a program in ANSI C that counts the number of times the characters \'a\' through \'z\' (lower case and upper case) occur in a text file. Use getchar() for input, and use input redirection for connecting the input file to the program.
Solution
#include <stdio.h>
int main()
{
FILE *fp;
char file[100];
char ch;
int char_count;
char_count = 0;
// Prompt user to enter filename
printf(\"Enter a filename :\");
gets(file);
// Open file in read-only mode
fp = fopen(file,\"r\");
if ( fp )
{
while ((ch=getc(fp)) != EOF) //Repeat until End Of File character is reached.
{
if (ch != \' \' && ch != \'\ \') // Increment character count if NOT new line or space
{
++char_count;
}
}
}
else
{
printf(\"Failed to open the file\ \");
}
printf(\"Characters : %d \ \", char_count);
getchar();
return(0);
}
