Hey there, I got homework (related to C), which asks to read different .txt files with different processes.
At the end of each child process, we must print .txt file's characters number
I tried this approach:
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char* argv[])
{
int i, j, FILE *fp;
char c;
for(j=1;j<argc;j++)
{
if (fork() == 0) // child process
{
if ((fp = fopen(argv[j],"r")) == NULL)
{
printf("Error when trying to open file");
exit(-1);
}
i = 0;
while((c=fgetc(fp)) != EOF) // tried while(!eof(fp)) but it didn't work
{ i++; }
printf("The characters number from %d text file is %d",j,i);
fclose(fp);
// even tried kill(getpid()) after closing the file, but it also didn't work
}
}
exit(0);
}
As predicted, if we run the program using
2 files as parameters, we get
4 prints..
The thing is, child processes aren't stopping, which is why I tried to kill each one of them after closing the file, but it didn't work either.
What am I missing here? I know exactly why it is wrong, but I don't know how to make each process read only 1 file.
Thanks,
Apidcloud
Answer:#include <stdio.h>
#include <stdlib.h>
void main(int argc, char* argv[])
{
int i, j, FILE *fp;
char c;
for(j=1;j<argc;j++)
{
if (fork() == 0) // child process
{
if ((fp = fopen(argv[j],"r")) == NULL)
{
printf("Error when trying to open file");
exit(-1);
}
fseek(fp, 0, SEEK_END); // this and the line below have better performance, and are also cleaner than a loop
i = ftell(fp);
printf("The characters number from %d text file is %d",j,i);
fclose(fp);
exit(0); // The reason why it wasn't working normally
}
}
exit(0);
}