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
USE C programming (pls label which file is libcipher.h and libcipher.c) Q4) A shift cipher is...
USE C programming (pls label which file is libcipher.h and libcipher.c) Q4) A shift cipher is one of the simplest encryption techniques in the field of cryptography. It is a cipher in which each letter in a plain text message is replaced by a letter some fixed number of positions up the alphabet (i.e., by right shifting the alphabetic characters in the plain text message). For example, with a right shift of 2, ’A’ is replaced by ’C’, ’B’ is...
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...
The code is in C programming language pls convert it into python. Thanks. Program --> #include...
The code is in C programming language pls convert it into python. Thanks. Program --> #include <stdio.h> #include <stdlib.h> void main() { //declare variables FILE *fileptr; char filename[15]; char charRead; char filedata[200],searchString[50]; int i=0,j=0,countNoOfWord=0,count=0; //enter the filename to be opened printf("Enter the filename to be opened \n"); scanf("%s", filename); /* open the file for reading */ fileptr = fopen(filename, "r"); //check file exit if (fileptr == NULL) { printf("Cannot open file \n"); exit(0); } charRead = fgetc(fileptr); //read the string...
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...
can you please do this lab? use lunix or C program its a continuation of a...
can you please do this lab? use lunix or C program its a continuation of a previous lab. the previous lab: Unix lab 4: compile and link multiple c or c++ files Please do the following tasks step by step: create a new directory named by inlab4 enter directory inlab4 create a new file named by reverse.c with the following contents and then close the file: /*reverse.c */ #include <stdio.h> reverse(char *before, char *after); main() {       char str[100];    /*Buffer...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's algorithm to ensure mutual exclusion in the respective critical sections of the two processes, and thereby eliminate the race condition. In order to implement Peterson's Algorithm, the two processes should share a boolean array calledflagwith two components and an integer variable called turn, all initialized suitably. We will create and access these shared variables using UNIX system calls relating to shared memory – shmget,...
Write a program that prompts the user to input a string and outputs the string in...
Write a program that prompts the user to input a string and outputs the string in uppercase letters. (Use dynamic arrays to store the string.) my code below: /* Your code from Chapter 8, exercise 5 is below. Rewrite the following code to using dynamic arrays. */ #include <iostream> #include <cstring> #include <cctype> using namespace std; int main() { //char str[81]; //creating memory for str array of size 80 using dynamic memory allocation char *str = new char[80]; int len;...
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...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4 enter directory inlab4 create a new file named by reverse.c with the following contents and then close the file: /*reverse.c */ #include <stdio.h> reverse(char *before, char *after); main() { char str[100]; /*Buffer to hold reversed string */ reverse("cat", str); /*Reverse the string "cat" */ printf("reverse(\"cat\")=%s\n", str); /*Display result */ reverse("noon", str); /*Reverse the string "noon" */ printf("reverse(\"noon\")=%s\n", str); /*Display result */ } reverse(char *before,...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT