Counting the number of times a character appears in a file

QUESTION:

Write a program to count the number of times a character appears in the File. (Case insensitive... 'a' and 'A' are considered to be the same)

Input and Output Format:
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output:
Enter the file name
test.txt
Enter the character to be counted
r
File 'test.txt' has 99 instances of letter 'r'.

SOLUTION:

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
    FILE *fptr;
    int d=0;
    char c;
    char ch;
    int ck;
    char b[100];
    printf("Enter the file name");
    scanf("%19s",b);
    fptr=fopen(b,"r");
    printf("\nEnter the character to be counted");
    scanf(" %c",&c);
    c=toupper(c);
    if(fptr==NULL)
        exit(-1);
    while((ck=fgetc(fptr))!=EOF)
    {
        ch=toupper(ck);
        if(c==ch || toupper(c)==ck)
            ++d;
    }
    fclose(fptr);
    printf("\nFile '%s' has %d instances of letter '%c'.",b,d,c);
    return 0;
}

Comments

  1. its not shoowing any compilation errors !! but the program is not working

    ReplyDelete

Post a Comment

Popular posts from this blog

Implementing a Fixed size Queue of maximum size 5 using an array

Implementing a Dynamically sized stack using array

Functions - Null Matrix