Write a C program, which reads the file “file.txt” and counts the frequency of e
ID: 3771029 • 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
the following code is written in main to execute the program:
int main()
{
char c;
int i,nwhite,nother;
int ndigit[10];
nwhite=nother=0;
for(i=0;i<10;++i)
ndigit[i]=0;
while((c=getchar()) != EOF)
if(c>='0' && c<='9')
++ndigit[c-'0'];
else if(c==' ' || c==' ' ||c=='t')
++nwhite;
else
++nother;
printf("digits=");
for(i=0;i<10;++i)
printf("%d",ndigit[i]);
printf(",white space=%d,other=%d ",nwhite,nother);
printf("the most frequent digit is %c ",'0'+mostfrequent(ndigit,10));
}
/*process and file read/write */
#include <unistd.h>
#include <sys/types.h>
#include <sys.stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char * argv[]){
int fd;
char c;
int i;
int pid;
char str[1000];
if(argc>1) /* argc is the number of command line parameters here */
fd=open(argv[1],O_RDWR,0); /* argv[1] is the first command line parameter */
else
fd=open("input.txt",O_RDWR,0); /* if no command line parameter is there then open the file input.txt */
if(fd==-1)
{
printf(" open file operation failed ");
return(0);
}
else
{
while (read(fd,&c,1))
{ printf(" i read a letter '%c' ",c);
}
}
pid=fork(); /* duplicate a process */
if(pid==0) /* child process */
{memset(str,'',1000); /*init str to be empty */
strcat(str," the child process writes the file. ");
write(fd,str,strlen(str));
close(fd);
}
else /* parent process */
{ printf(" the parents process outputs to the terminal. ");
}
return(1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.