簡體   English   中英

C程序,用於使用獲取分段錯誤錯誤的線程來計算文件中單詞出現的次數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM