简体   繁体   中英

C program not giving right output

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>


struct thread_data{
    FILE *fp;
    long int offset;
    int start;
    int blockSize;
    //struct word maybe?
 };

int words=0;  

void *countFrequency(void* data){

struct thread_data* td=data;
char *buffer = malloc(td->blockSize);

int i,c;
i=0;c=0;
enum states { WHITESPACE, WORD };
int state = WHITESPACE;

fseek(td->fp, td->offset, td->start);

    char last = ' '; 
    while ((fread(buffer, td->blockSize, 1, td->fp))==1){

        if ( buffer[0]== ' ' || buffer[0] == '\t'  ){
        state = WHITESPACE;
        }
        else if (buffer[0]=='\n'){
        //newLine++;
            state = WHITESPACE;
        }
        else {
            if ( state == WHITESPACE ){
                words++;
            }
            state = WORD;
        }
        last = buffer[0];
}
free(buffer);

pthread_exit(NULL);

return NULL;
}

int main(int argc, char **argv){

    int nthreads, x, id, blockSize,len;
    //void *state;
    FILE *fp;
    pthread_t *threads;



    fp = fopen("file1.txt","r");

    printf("Enter the number of threads: ");
    scanf("%d",&nthreads);
    struct thread_data data[nthreads];
    threads = malloc(nthreads*sizeof(pthread_t));

    fseek(fp, 0, SEEK_END);
    len = ftell(fp);  
    printf("len= %d\n",len);

    blockSize=(len+nthreads-1)/nthreads;
    printf("size= %d\n",blockSize);

    for(id = 0; id < nthreads; id++){

        data[id].fp=fp;
        data[id].offset = blockSize;
        data[id].start = id*blockSize+1;
            //maybe data[id]. word struct
        }
    //LAST THREAD
    data[nthreads-1].start=(nthreads-1)*blockSize+1;

    for(id = 0; id < nthreads; id++)
        pthread_create(&threads[id], NULL, &countFrequency,&data[id]);

    for(id = 0; id < nthreads; id++)
        pthread_join(threads[id],NULL);

    fclose(fp);


    printf("%d\n",words); 
    return 0;  
    }

I had a segmentation fault that i fixed in this program but now when I run it, i get 0 words, which is incorrect bc there are about a million words in the text file. Can anyone tell me why it is giving me an incorrect word count? Thanks!

nthreads的值在nthreads位置未定义

struct thread_data data[nthreads];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM