89.3k views
4 votes
(main.c File)

Counting the character occurrences in a file
For this task you are asked to write a program that will open a file called “story.txt”
and count the number of occurrences of each letter from the alphabet in this file.
At the end your program will output the following report:
Number of occurrences for the alphabets:
a was used – times.
b was used – times.
c was used – times…. …and so, on
Assume the file contains only lower-case letters and for simplicity just a single
paragraph. Your program should keep a counter associated with each letter of the
alphabet (26 counters) [Hint: Use array]
Your program should also print a histogram of characters count by adding
a new function print Histogram (int counters []). This function receives the
counters from the previous task and instead of printing the number of times each
character was used, prints a histogram of the counters. An example histogram for
three letters is shown below) [Hint: Use the extended asci character 254]

1 Answer

1 vote

Answer:

C code

Step-by-step explanation:

#include <stdio.h>

void histrogram(int counters[])

{

int i,j;

int count;

for(i=0;i<26;i++)

{

count=counters[i];

printf("%c ",i+97);

for(j=0;j<count;j++)

{

printf("="); //= is used

}

printf("\\");

}

}

int main()

{

FILE* fp;

int i;

int arr[26];

char c;

int val;

// Open the file

fp = fopen("story.txt", "r");

if (fp == NULL) {

printf("Could not open file ");

return 0;

}

else

{

for(i=0;i<26;i++)

arr[i]=0;

for (c = getc(fp); c != EOF; c = getc(fp))

{

if(c>='a' && c<='z')

{

val = c-97;

//printf("%d ",val);

arr[val]++;

}

}

histrogram(arr);

}

}

User Morteza
by
4.4k points