gpt4 book ai didi

使用线程计算文件中单词出现次数的 C 程序出现段错误

转载 作者:行者123 更新时间:2023-11-30 17:07:27 24 4
gpt4 key购买 nike

所以我有以下问题:实现一个程序,该程序获取文件名作为参数,后跟单词。对于每个单词,创建一个单独的线程来计算其在给定文件中的出现次数。打印出所有单词出现次数的总和。

我也不确定我的代码格式是否确实正确。我试图弄清楚如何计算给定文本文件中的每个单词。我正在尝试测试这段代码,但我从中得到了一些错误,最大的是段错误。如果您有任何指示、建议或帮助,请告诉我。

我的代码是:

#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 *。这几乎肯定会导致段错误。 – 凯勒姆

关于使用线程计算文件中单词出现次数的 C 程序出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com