Write a C program, which reads the file “file.txt” and counts the frequency of e
ID: 3771274 • Letter: W
Question
Write a C program, which reads the file “file.txt” and counts the frequency of each digit (0, 1, 2, ..., 9)/letter (A/a, B/b, …, Z/z). Then, use fork() to duplicate a child process to write the most frequent digit/letter at the end of the file “file.txt”. The parent process output the frequency of each digit/letter to the terminal. You need to call the function “mostfrequent” (which is used for calculating the most frequent digit/letter defined below) in your program.
int mostfrequent(int * a, int length)
/*length is the length of the array. The function returns the index of the largest value of array a.*/
{
int index=0;
int max=a[0];
int i;
for(i=1;i<length;i++)
{
if (a[i]>max)
{
max = a[i];
index = i;
}
}
return index;
}
Explanation / Answer
Input : "input.txt"
Program :
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h> /* pid_t */
#include <unistd.h> /* _exit, fork */
int mostfrequent(int * a, int length)
{
int index=0;
int max=a[0];
int i;
for(i=1;i<length;i++){
if (a[i]>max){
max = a[i];
index = i;
}
}
return index;
}
int main(){
pid_t pid;
FILE *fp,*fp1;
char ch;
int k;
fp = fopen("input.txt","r");
//fp1 = fopen("input.txt", "a");
int A[36] = {0};
while((ch = fgetc(fp)) != EOF){
// printf("%c",ch);
if(isalpha(ch)){
k =tolower(ch)-'a';
A[k]++;
}
if(isdigit(ch)){
k=ch-'0';
A[k+26]++;
}
}
fclose(fp);
pid = fork();
if (pid == -1){
/* Error: When fork() returns -1*/
//fprintf(stderr, "can't fork, error %d ", errno);
exit(EXIT_FAILURE);
}
else if (pid == 0){
fp1 = fopen("input.txt", "a");
int max_index = mostfrequent(A,36);
//printf(" %d",max_index);
fprintf(fp1, "%c",max_index+'a');
}
else{
int i;
for(i=0;i<26;i++){
if(A[i]!=0)
printf("%c = %d ",i+'a',A[i]);
}
for(i=26;i<36;i++){
if(A[i]!=0)
printf("%d = %d ",i-26,A[i]);
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.