![](/img/trans.png)
[英]Segmentation fault error in a program for counting no of occurences of a word in a file using threads
[英]C program for counting the number of occurrences of a word in a file using threads getting segmentation fault error
因此,我遇到以下问题:实现一个程序,该程序将文件名后跟单词作为参数。 为每个单词创建一个单独的线程以计算其在给定文件中的出现次数,并打印出所有单词的出现总数。
我也不确定我的代码是否正确格式化。 我试图弄清楚如何在给定的文本文件中对每个单词进行计数。 我正在尝试测试此代码,但从中得到了几个错误,最大的是分段错误。 如果您有任何指示,建议或帮助,请告诉我。
我的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mtx; // used by each of the three threads to prevent other threads from accessing global_sum during their additions
int global_sum = 0;
typedef struct{
char* word;
char* filename;
}MyStruct;
void *count(void*str)
{
MyStruct *struc;
struc = (MyStruct*)str;
const char *myfile = struc->filename;
FILE *f;
int count=0, j;
char buf[50], read[100];
// myfile[strlen(myfile)-1]='\0';
if(!(f=fopen(myfile,"rt"))){
printf("Wrong file name");
}
else
printf("File opened successfully\n");
for(j=0; fgets(read, 10, f)!=NULL; j++){
if (strcmp(read[j],struc->word)==0)
count++;
}
printf("the no of words is: %d \n",count);
pthread_mutex_lock(&mtx); // lock the mutex, to prevent other threads from accessing global_sum
global_sum += count; // add thread's count result to global_sum
pthread_mutex_unlock(&mtx); // unlock the mutex, to allow other threads to access the variable
}
int main(int argc, char* argv[]) {
int i;
MyStruct str;
pthread_mutex_init(&mtx, NULL); // initialize mutex
pthread_t threads[argc-1]; // declare threads array
for (i=0;i<argc-2;i++){
str.filename = argv[1];
str.word = argv[i+2];
pthread_create(&threads[i], NULL, count, &str);
}
for (i = 0; i < argc-1; ++i)
pthread_join(threads[i], NULL);
printf("The global sum is %d.\n", global_sum); // print global sum
pthread_mutex_destroy(&mtx); // destroy the mutex
return 0;
}
今天的第二点建议是仔细查看编译器给您的警告并留意这些警告。 strcmp(read[j],struc->word)
您的编译器必须警告您这是错误的。 您将传递一个char
作为第一个参数,而不是const char *
。 几乎可以肯定会导致段错误。 –贝壳
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.