Write a C program, which reads the file “file.txt” and counts the frequency of e
ID: 3769877 • 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;
}
Example: Process and file read and write.
#include <unistd.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.*/
fd=open(argv[1], O_RDWR, 0); /*argv[1] is the first command line parameter.*/
else
fd=open("test.txt", O_RDWR, 0);/*if no command line parameter, open file input.txt*/
if (fd==-1)
{
printf("Open file failed. ");
return(0);
}
else
{
while (read(fd,&c,1))
{
printf("I read a letter '%c' ",c);
}
strcat(str,"This is a string ");
write(fd,str,strlen(str)); //write a string to file
write(fd,&c,1);//write a char to file
}
return(1);
}
Example: Creating multiple child processes
#include <stdio.h>
int main () {
int pid,i;
for ( i=0; i<10; i++) {
pid=fork();
if (pid==0||pid==-1) {
break;
}
}
if (pid==-1) {
printf("error ");
} else if(pid==0){
printf("%d---",i);
switch (i%3) {
case 0:
printf("I am child process A ");
// child process code here...
break;
case 1:
printf("I am child process B ");
// child process code here...
break;
case 2:
printf("I am child process C ");
// child process code here...
break;
}
} else {
printf("I am parent process ");
}
}
Explanation / Answer
using namespace std;
int counter = 0;
pid_t pid = fork();
}
void fork_test()
{
if (fork() !=0)
{
if (fork () !=0)
fork();
else
printf(“hello 1 ”);
}
else
{
if(fork() !=0)
{
printf(“letters ”);
}
else
{
fork();
}
}
printf(digits ”);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.