我需要编写一个C程序,该程序将计算在命令行上声明的每个文件中的单词数量。我专门为每个文件创建一个进程,然后读取该文件中的单词数量,父进程需要等待并打印出总数。这是我的代码:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <errno.h>
4
5 int main(int argc, char *argv[])
6 {
7 int i;
8 int pid;
9 int total_ammount_of_words;
10 FILE *current_file;
11
12 //Create processes for each file on the command line
13 for(i = 1; i < argc; i++)
14 {
15 pid = fork();
16 if(pid == -1) //Error
17 {
18 exit(-1);
19 }
20 else if(pid == 0) //Children
21 {
22 current_file = fopen(argv[i], "r");
23 total_ammount_of_words += countWords(current_file);
24 printf("Child Process for File %s: number of words is: %i\n", argv[i], c ountWords(current_file));
25 exit(0);
26 }
27 else //Parent
28 {
29 wait(NULL);
30 }
31
32 }
33 printf("All %i files have been counted!\n Total Ammount of Words: %i\n", (argc-1), total _ammount_of_words);
34
35 }
36
37 int countWords(FILE *file){
38 int count = 0;
39 char character;
40 while((character = fgetc(file)) != EOF){
41 if(character == '\n' || character == ' ')
42 count++;
43 }
44 return count;
45 }
这是我在命令行上声明的内容(每个文件中只有一个字,因此我的输出应等于3):
assign1 cat.txt dog.txt fish.txt
我不明白为什么我一直把这个作为输出:
Child Process for File cat.txt: number of words is: 0
Child Process for File dog.txt: number of words is: 0
Child Process for File fish.txt: number of words is: 0
All 3 files have been counted!
Total Amount of Words: 32767
我不明白为什么我的代码没有正确计算单词数量? 我用谷歌搜索已经计算了文件中所有单词的其他人,并且我完全按照它们来做。