Question

C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total...

C Program

Write a program to count the frequency of each alphabet letter (A-Z a-z, total 52 case sensitive) and five special characters (‘.’, ‘,’, ‘:’, ‘;’ and ‘!’) in all the .txt files under a given directory. The program should include a header count.h, alphabetcount.c to count the frequency of alphabet letters; and specialcharcount.c to count the frequency of special characters. Please only add code to where it says //ADDCODEHERE and keep function names the same.

I have also included testalphabetcount.c and testspecialcharcount.c which will be ran to test the program. Please do not modify these files. You will need to modify the paths in order to test, though.

------------------------------------------------count.h------------------------------------------------

#include <stdio.h>

#define ALPHABETSIZE 52 //The total number of alphabetical letter from A - Z and a - z(case sensitive)
#define SPECIALCHARSIZE 5 // The number of these special characters ',' '.' ';' ':' '!'

void alphabetlettercount(char *path, char *filetowrite, long alphabetfreq[]);
void specialcharcount(char *path, char *filetowrite, long charfreq[]);


-------------------------------------------------specialcharcount.c------------------------------------------------

#include <stdio.h>
#include "count.h"

void specialcharcount(char *path, char *filetowrite, long charfreq[])
{

   //ADDCODEHERE
      
}

/**
The specialcharcount function counts the frequency of the following 5 special characters:
',' '.' ':' ';' '!'

in all the .txt files under directory of the given path and write the results to a file named as filetowrite.
  
Input:
  
path - a pointer to a char string [a character array] specifying the path of the directory; and
filetowrite - a pointer to a char string [a character array] specifying the file where results should be written in.
alphabetfreq - a pointer to a long array storing the frequency of the above 5 special characters
  
charfreq[0]: the frequency of ','
charfreq[1]: the frequency of '.'
charfreq[2]: the frequency of ':'
charfreq[3]: the frequency of ';'
charfreq[4]: the frequency of '!'

  
Output: a new file named as filetowrite with the frequency of the above special characters written in
  
Steps recommended to finish the function:
1) Find all the files ending with .txt and store in filelist.
2) Read all files in the filelist one by one and count the frequency of each alphabet letter only (a - z). The array
long alphabetfreq[] always has the up-to-date frequencies of alphabet letters counted so far. If the letter is upper case, convert
it to lower case first.
3) Write the result in the output file: filetowrite in following format:
  
character -> frequency

example:
, -> 20
. -> 11
: -> 20
; -> 11
! -> 12   

Assumption:
1) You can assume there is no sub-directory under the given path so you don't have to search the files
recursively.
2) Only .txt files are counted and other types of files should be ignored.
  
*/

------------------------------------------------alphabetcount.c------------------------------------------------

#include <stdio.h>
#include "count.h"

/**
The alphabetlettercount function counts the frequency of each alphabet letter (A-Z a-z, case sensitive) in all the .txt files under
directory of the given path and write the results to a file named as filetowrite.
  
Input:
path - a pointer to a char string [a character array] specifying the path of the directory; and
filetowrite - a pointer to a char string [a character array] specifying the file where results should be written in.
alphabetfreq - a pointer to a long array storing the frequency of each alphabet letter from A - Z a - z:
alphabetfreq[0]: the frequency of 'A'
alphabetfreq[1]: the frequency of 'B'
... ...
alphabetfreq[25]:the frequency of 'Z'
alphabetfreq[26]:the frequency of 'a'
... ...
alphabetfreq[51]:the frequency of 'z'
  
Output: a new file named as filetowrite with the frequency of each alphabet letter written in
  
Steps recommended to finish the function:
1) Find all the files ending with .txt and store in filelist.
2) Read all files in the filelist one by one and count the frequency of each alphabet letter only (A-Z a - z). The array
long alphabetfreq[] always has the up-to-date frequencies of alphabet letters counted so far.
3) Write the result in the output file: filetowrite in following format:
  
letter -> frequency

example:
A -> 200
B -> 101
... ...

Assumption:
1) You can assume there is no sub-directory under the given path so you don't have to search the files
recursively.
2) Only .txt files are counted and other types of files should be ignored.
  
*/
void alphabetlettercount(char *path, char *filetowrite, long alphabetfreq[])
{
  
   //ADDCODEHERE
      
  
}

------------------------------------------------testalphabetcount.c------------------------------------------------

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include<unistd.h>
#include <stdbool.h>
#include "count.h"

/*
* Print the frequencies of alphabetical characters stored in array: charfreq[] to output screen in the format as:
* letter -> frequency (one letter a line)
* Input: charfreq - array having the frequency of each alphabet letter
size - the total number of alphabet letters
* example:
* a -> 20
* b -> 30
*/

void displayalphabetfreq(long charfreq[], int size)
{
   for(int i = 0; i < size/2; i++) // print upper case letter frequency
   {
       printf("%c -> %d\n", (char)(i+65), charfreq[i]);
   }

    for(int i = size/2; i < size; i++) // print lower case letter frequency
   {
       printf("%c -> %d\n", (char)(i+65 + 6), charfreq[i]);
   }
}

int main()
{
  
   char *path = "ADD PATH HERE"; // the data *.txt files are under this folder
   char *filetowrite = "ADD PATH HERE"; // the frequency of all alphabetical letters will be written in this file
  
   long alphabetfreq[ALPHABETSIZE] = {0}; // array to store the frequency of each alphablet letter
  
  
   alphabetlettercount(path, filetowrite, alphabetfreq); // process the data files
  
   displayalphabetfreq(alphabetfreq, ALPHABETSIZE); // print the frequency stored in the array to output screen
}


------------------------------------------------testspecialcharcount.c------------------------------------------------
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include<unistd.h>
#include <stdbool.h>
#include "count.h"


/*
* This function prints the frequency stored in array charfreq[] to output screen.
* Input: charfreq - array having the frequency of special characters
size - the total number of special characters
* example:
* a -> 20
* b -> 30
*/
void displayspecialcharfreq(long charfreq[], int size)
{  
   for(int i = 0; i < size; i++)
   {
       switch(i)
       {
           case 0:
               printf(", -> %d\n", charfreq[i]);
               break;
           case 1:
               printf(". -> %d\n", charfreq[i]);
               break;
           case 2:
               printf(": -> %d\n", charfreq[i]);
               break;
           case 3:
               printf("; -> %d\n", charfreq[i]);
               break;
           case 4:
               printf("! -> %d\n", charfreq[i]);
               break;
       }      
   }
}

int main()
{
   char *path = "ADD PATH HERE"; // the path of the directory including the *.txt files to be processed
   char *filetowrite = "ADD PATH HERE"; // the frequency of all alphabetical letters will be written in this file
  
   long charfreq[SPECIALCHARSIZE] = {0}; // array to store the frequency of 5 special characters
  
   specialcharcount(path, filetowrite, charfreq); // count the frequency of special characters and write into file
  
   displayspecialcharfreq(charfreq, SPECIALCHARSIZE); // print the array to output screen  
}

Homework Answers

Answer #1

Working code implemented in C and appropriate comments provided for better understanding:

Here I am attaching code for these files:

  • count.h
  • alphabetcount.c
  • specialcharcount.c
  • testalphabetcount.c
  • testspecialcharcount.c

Source code for count.h:

/* charcount.h - This header file include type definitions (including function prototypes) and macros
used for the programing assignment zero.
*/

#include <stdio.h>

#define ALPHABETSIZE 26 //The total number of alphabetical letter from a - z (case insensitive)
#define SPECIALCHARSIZE 5 // The number of these special characters ',' '.' ';' ':' '!'

void alphabetlettercount(char *path, char *filetowrite, long alphabetfreq[]);
/**
The alphabetlettercount function counts the frequency of each alphabet letter (a-z, case insensitive) in all the .txt files under
directory of the given path and write the results to a file named as filetowrite.
  
Input:
path - a pointer to a char string [a character array] specifying the path of the directory; and
filetowrite - a pointer to a char string [a character array] specifying the file where results should be written in.
alphabetfreq - a pointer to a long array storing the frequency of each alphabet letter from a - z:
alphabetfreq[0]: the frequency of 'a'
alphabetfreq[1]: the frequency of 'b'
... ...
alphabetfreq[25]:the frequency of 'z'

  
Output: a new file named as filetowrite with the frequency of each alphabet letter written in

*/

void specialcharcount(char *path, char *filetowrite, long charfreq[]);
/**
The specialcharcount function counts the frequency of the following 5 special characters:
',' '.' ':' ';' '!'

in all the .txt files under directory of the given path and write the results to a file named as filetowrite.
  
Input:
  
path - a pointer to a char string [a character array] specifying the path of the directory; and
filetowrite - a pointer to a char string [a character array] specifying the file where results should be written in.
alphabetfreq - a pointer to a long array storing the frequency of the above 5 special characters
  
charfreq[0]: the frequency of ','
charfreq[1]: the frequency of '.'
charfreq[2]: the frequency of ':'
charfreq[3]: the frequency of ';'
charfreq[4]: the frequency of '!'

  
Output: a new file named as filetowrite with the frequency of the above special characters written in
  
Steps recommended to finish the function:
1) Find all the files ending with .txt and store in filelist.
2) Read all files in the filelist one by one and count the frequency of each alphabet letter only (a - z). The array
long alphabetfreq[] always has the up-to-date frequencies of alphabet letters counted so far. If the letter is upper case, convert
it to lower case first.
3) Write the result in the output file: filetowrite in following format:
  
character -> frequency

example:
, -> 20
. -> 11
: -> 20
; -> 11
! -> 12   

Assumption:
1) You can assume there is no sub-directory under the given path so you don't have to search the files
recursively.
2) Only .txt files are counted and other types of files should be ignored.
  
*/

Source code for alphabetcount.c:

/*
* alphabetcount.c - this file implements the alphabetlettercount function.
*/

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include "count.h"

void alphabetlettercount(char *path, char *filetowrite, long alphabetfreq[])
{
DIR *d;
char *filename;
char *fil;
struct dirent *dir; //directory opening process
d = opendir(path);
if(d != NULL) {
while((dir = readdir(d)) != NULL) {
filename = dir->d_name; //assigns current name to string filename
size_t t = strlen(filename) - 3; //checks for .txt extentsion
int ctr = 0;
while(t < strlen(filename)) {
if(!(filename[t] == 't' || filename[t] == 'x'))
continue;
else {
ctr++; //adds the current letter to a counter
}
t++;
}
if(ctr == 3) { //counter will only be 3 if "txt" is read
fil = dir->d_name; //immediately stores validated file to be read
char p[256];
strcpy(p, path); //concatenates the full data directory to p
strcat(p, "/");
strcat(p, fil);
FILE *f = fopen(p, "r"); //opens the file path for reading
if(f == NULL) { //can't open file, abort
return;
}
int c = fgetc(f); //grabs the first character
while(!feof(f)) {
if((c >= 65) && (c <= 90)) //checks if char's ascii value is uppercase, and changes it to lowercase
c = c + 32;
if((c >= 97) && (c <= 122)) { //if alphabet letter is found
alphabetfreq[c - 97] = (long) alphabetfreq[c - 97] + 1; //increments desired character counter. c-97 corresponds to each lowercase's location in the array
}
c = fgetc(f); //re-initializes fgetc for next character in while loop
}
  
fclose(f);
FILE *g = fopen(filetowrite, "w"); //opens result.txt for writing
   for(int i = 0; i < 26; i++) { //loops through entire alphabetfreq
       fprintf(f, "%c -> %ld\n", (char)(i+97), alphabetfreq[i]); //formatted writing
   }   
  
fclose(g);
}
}
}
closedir(d); //close directory
}

/**
The alphabetlettercount function counts the frequency of each alphabet letter (a-z, case insensitive) in all the .txt files under
directory of the given path and write the results to a file named as filetowrite.
  
Input:
path - a pointer to a char string [a character array] specifying the path of the directory; and
filetowrite - a pointer to a char string [a character array] specifying the file where results should be written in.
alphabetfreq - a pointer to a long array storing the frequency of each alphabet letter from a - z:
alphabetfreq[0]: the frequency of 'a'
alphabetfreq[1]: the frequency of 'b'
... ...
alphabetfreq[25]:the frequency of 'z'

  
Output: a new file named as filetowrite with the frequency of each alphabet letter written in
  
Steps recommended to finish the function:
1) Find all the files ending with .txt and store in filelist.
2) Read all files in the filelist one by one and count the frequency of each alphabet letter only (a - z). The array
long alphabetfreq[] always has the up-to-date frequencies of alphabet letters counted so far. If the letter is upper case, convert
it to lower case first.
3) Write the result in the output file: filetowrite in following format:
  
letter -> frequency

example:
a -> 200
b -> 101
... ...

Assumption:
1) You can assume there is no sub-directory under the given path so you don't have to search the files
recursively.
2) Only .txt files are counted and other types of files should be ignored.
  
*/

Source code for specialcharcount.c:

/*
* specialcharcount.c - this file implements the specialcharcount function.
*/


#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include "count.h"

void specialcharcount(char *path, char *filetowrite, long charfreq[])
{
DIR *d;
char *filename;
char *fil; //stored filename
struct dirent *dir; //directory opening process
d = opendir(path);
if(d != NULL) {
while((dir = readdir(d)) != NULL) {
filename = dir->d_name; //assigns current name to string filename
size_t t = strlen(filename) - 3; //checks extension for .txt
int ctr = 0;
while(t < strlen(filename)) {
if(!(filename[t] == 't' || filename[t] == 'x'))
continue;
else {
ctr++; //adds the current letter to a counter
}
t++;
}
if(ctr == 3) { //counter will only be 3 if "txt" is read
fil = dir->d_name; //once file checks out, it is immediately read. Using an array has lead to several issues such as data corruption, so I switched to this.
char p[256];
strcpy(p, path); //concatenates the entire filepath to p
strcat(p, "/");
strcat(p, fil);
FILE *f = fopen(p, "r"); //opens the file path for reading
if(f == NULL) { //can't open file, abort
return;
}
int c = fgetc(f); //grabs the first character
while(!feof(f)) {
if(c == 44) {
charfreq[0] = (long) charfreq[0] + 1; //increments desired character counter
}
else if(c == 46) {
charfreq[1] = (long) charfreq[1] + 1;
}
else if(c == 58) {
charfreq[2] = (long) charfreq[2] + 1;
}
else if(c == 59) {
charfreq[3] = (long) charfreq[3] + 1;
}
else if(c == 33) {
charfreq[4] = (long) charfreq[4] + 1;
}
c = fgetc(f); //re-initializes fgetc for next character in while loop
}
  
fclose(f); //close
FILE *g = fopen(filetowrite, "w"); //opens result.txt for writing
       fprintf(f, ", -> %ld\n", charfreq[0]); //formatted writing
fprintf(f, ". -> %ld\n", charfreq[1]);
fprintf(f, ": -> %ld\n", charfreq[2]);
fprintf(f, "; -> %ld\n", charfreq[3]);
fprintf(f, "! -> %ld\n", charfreq[4]);
fclose(g);
  
}
}
}
closedir(d); //close directory
      
}
/**
The specialcharcount function counts the frequency of the following 5 special characters:
',' '.' ':' ';' '!'

in all the .txt files under directory of the given path and write the results to a file named as filetowrite.
  
Input:
  
path - a pointer to a char string [a character array] specifying the path of the directory; and
filetowrite - a pointer to a char string [a character array] specifying the file where results should be written in.
alphabetfreq - a pointer to a long array storing the frequency of the above 5 special characters
  
charfreq[0]: the frequency of ','
charfreq[1]: the frequency of '.'
charfreq[2]: the frequency of ':'
charfreq[3]: the frequency of ';'
charfreq[4]: the frequency of '!'

  
Output: a new file named as filetowrite with the frequency of the above special characters written in
  
Steps recommended to finish the function:
1) Find all the files ending with .txt and store in filelist.
2) Read all files in the filelist one by one and count the frequency of each alphabet letter only (a - z). The array
long alphabetfreq[] always has the up-to-date frequencies of alphabet letters counted so far. If the letter is upper case, convert
it to lower case first.
3) Write the result in the output file: filetowrite in following format:
  
character -> frequency

example:
, -> 20
. -> 11
: -> 20
; -> 11
! -> 12   

Assumption:
1) You can assume there is no sub-directory under the given path so you don't have to search the files
recursively.
2) Only .txt files are counted and other types of files should be ignored.
  
*/

Source code for testalphabetcount.c:

/* This program is to test alphabetcount function.
*
*/

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include<unistd.h>
#include <stdbool.h>
#include "count.h"

/*
* Print the frequencies of alphabetical characters stored in array: charfreq[] to output screen in the format as:
* letter -> frequency (one letter a line)
* Input: charfreq - array having the frequency of each alphabet letter
size - the total number of alphabet letters
* example:
* a -> 20
* b -> 30
*/

void displayalphabetfreq(long charfreq[], int size)
{
   for(int i = 0; i < size; i++)
   {
       printf("%c -> %d\n", (char)(i+97), charfreq[i]);
   }
}

int main()
{
  
   char *path = "../data"; // the data *.txt files are under this folder
   char *filetowrite = "result.txt"; // the frequency of all alphabetical letters will be written in this file
  
   long alphabetfreq[ALPHABETSIZE] = {0}; // array to store the frequency of each alphablet letter
  
  
   alphabetlettercount(path, filetowrite, alphabetfreq); // process the data files
  
   displayalphabetfreq(alphabetfreq, ALPHABETSIZE); // print the frequency stored in the array to output screen
}

Source code for testspecialcharcount.c:

/* This program is to test specialcharcount function.
*
*/

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include<unistd.h>
#include <stdbool.h>
#include "count.h"


/*
* This function prints the frequency stored in array charfreq[] to output screen.
* Input: charfreq - array having the frequency of special characters
size - the total number of special characters
* example:
* a -> 20
* b -> 30
*/
void displayspecialcharfreq(long charfreq[], int size)
{  
   for(int i = 0; i < size; i++)
   {
       switch(i)
       {
           case 0:
               printf(", -> %d\n", charfreq[i]);
               break;
           case 1:
               printf(". -> %d\n", charfreq[i]);
               break;
           case 2:
               printf(": -> %d\n", charfreq[i]);
               break;
           case 3:
               printf("; -> %d\n", charfreq[i]);
               break;
           case 4:
               printf("! -> %d\n", charfreq[i]);
               break;
       }      
   }
}

int main()
{
   char *path = "../data"; // the path of the directory including the *.txt files to be processed
   char *filetowrite = "specialresult.txt"; // the frequency of all alphabetical letters will be written in this file
  
   long charfreq[SPECIALCHARSIZE] = {0}; // array to store the frequency of 5 special characters
  
   specialcharcount(path, filetowrite, charfreq); // count the frequency of special characters and write into file
  
   displayspecialcharfreq(charfreq, SPECIALCHARSIZE); // print the array to output screen  
}

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
LANGUAGE C The codes below reads another .c or .txt file. Then, it will read the...
LANGUAGE C The codes below reads another .c or .txt file. Then, it will read the contents of every line and store the contents into a string array. Example: .c file that is to be read: #include <stdio.h> int main(){    printf("Hello World");    return ; } _______________(END OF THE FILE)_______________ Therefore, the code will read the contents above and store the contents in every line into an array, such that.... array[0] = "#include <stdio.h>\n" array[1] = "\n" array[2] ="int...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
For the following code in C, I want a function that can find "america" from the...
For the following code in C, I want a function that can find "america" from the char array, and print "america is on the list" else "america is not on the list" (Is case sensitive). I also want a function to free the memory at the end of the program. #include <stdio.h> #include <stdlib.h> struct Node { void *data; struct Node *next; }; struct List { struct Node *head; }; static inline void initialize(struct List *list) { list->head = 0;...
Please answer the following C question: Read the following files called array-utils5A.c and array-utils5A.h. Build an...
Please answer the following C question: Read the following files called array-utils5A.c and array-utils5A.h. Build an executable with gcc -Wall -DUNIT_TESTS=1 array-utils5A.c The definitions for is_reverse_sorted and all_different are both defective. Rewrite the definitions so that they are correct. The definition for is_alternating is missing. Write a correct definition for that function, and add unit tests for it, using the unit tests for is_reverse_sorted and all_different as models. Please explain the logic errors present in in the definition of is_reverse_sorted...
I am trying to write a program in C language but keep running into errors. Any...
I am trying to write a program in C language but keep running into errors. Any help would be awesome. here is my code I have so far. #include <stdio.h> #include <conio.h> #include <string.h> int main(){    int lenght, i = 0, state = 0;    char line[100];    printf("enter the string for checking of comment line: \n");    gets(line);    while(i < strline(line)){        switch(state){            case 0: if (line[i] == '/'){               ...
Please answer the following C question: There is a documented prototype for a function called get_a_line...
Please answer the following C question: There is a documented prototype for a function called get_a_line in the code below. Write a definition for get_a_line—the only function called from that definition should be fgetc. #include <stdio.h> #include <string.h> #define BUFFER_ARRAY_SIZE 10 int get_a_line(char *s, int size, FILE *stream); // Does what fgets does, using repeated calls to fgetc, but // provides a more useful return value than fgets does. // // REQUIRES // size > 1. // s points to...
In C language: Partially finished program is given below. The second and third parameters of the...
In C language: Partially finished program is given below. The second and third parameters of the count() function need to be pointer parameters. However, the programmer forgot to write the necessary ampersands and asterisks in the prototype, call, function header, and function code. Add these characters where needed so that changes made to the parameters adults and teens actually change the underlying variables in the main program. #include #define MAX 10 void count( int ages[], int adults, int teens );...
C Programming I am trying to also print the frequency and the occurrence of an input...
C Programming I am trying to also print the frequency and the occurrence of an input text file. I got the occurrence to but cant get the frequency. Formula for frequency is "Occurrence / total input count", this is the percentage of occurrence. Can someone please help me to get the frequency to work. Code: int freq[26] = {0}; fgets(input1, 10000, (FILE*)MyFile); for(i=0; i< strlen(input); i++) { freq[input[i]-'a']++; count++; } printf("Text count = %d", count); printf("\n"); printf("Frequency of plain text\n");...
Using the C programming language implement Heapsort in the manner described in class. Here is some...
Using the C programming language implement Heapsort in the manner described in class. Here is some example code to use as a guideline. Remember, you need only implement the sort algorithm, both the comparison and main functions have been provided. /* * * after splitting this file into the five source files: * * srt.h, main.c, srtbubb.c, srtinsr.c, srtmerg.c * * compile using the command: * * gcc -std=c99 -DRAND -DPRNT -DTYPE=(float | double) -D(BUBB | HEAP | INSR |...
Answer the questions based on the program given below. a) Write the function prototype of fnFunny...
Answer the questions based on the program given below. a) Write the function prototype of fnFunny function. b) Write the output produced by the above program #include <stdio.h> int main (void){       unsigned short i =4;       unsigned long j = 6 ;       short k = 2 ;       k = fnFunny ( i , j );       printf("i = %hu, j = %lu, k = %hi\n", i, j, k);       return 0; } short fnFunny (unsigned short i,...