How to read a certain number of rows in C?

0

This is my code that reads and searches for a particular word,

void* pthread_wordCounter(void* parameter){

    int count = 0;
    size_t linesize = 0;
    char *linebuf = 0;
    ssize_t linelenght=0;

    static const char filename[]= "pg76.txt";
    FILE *file = fopen(filename, "r"); //open file
    if (file!=NULL){
        while ((linelenght = getline(&linebuf, &linesize, file))>0) {
            if (strstr(linebuf,"elephant")!=NULL) //finds if there is the word on the line
            {
                count++;
            }
        }
        fclose(file); //close file
        printf("The total amount of words is %d \n", count);
    }
    else{
        perror(filename);
    }
    return 0;

}

How should I read only 1000 lines at a time (assuming the file has more than 1000 lines) and send this block of lines to another function that will search the word?

    
asked by anonymous 15.10.2015 / 00:04

1 answer

0

Well, to read 1000 lines you should first think about the criticism of the case where the pass you read does not have 1000 lines.

So I suggest you do the following in your code:

void* pthread_wordCounter(void* parameter){

int count = 0;
size_t linesize = 0;
char *linebuf = 0;
ssize_t linelenght=0;
int counter = 0;

static const char filename[]= "pg76.txt";
FILE *file = fopen(filename, "r"); //open file
if (file!=NULL){
while((linelenght = getline(&linebuf, &linesize, file))>0){
        while ((linelenght = getline(&linebuf, &linesize, file))>0 && counter < 999) {
            counter++;
        }

    // AO FINAL ELE PODE FAZER ALGUMA COISA AQUI.

}
    fclose(file); //close file
    printf("The total amount of words is %d \n", count);
}
else{
    perror(filename);
}
return 0;

Note that I've added two things. An internal counter that goes up to 999 and an external while that will read the first line. What is being done is, the code will both read 1000 lines and do what you want in the location indicated by the comment as it will stop when the EOF arrives.

I hope I have helped if it is still difficult to suggest that you specify a little more the problem for the community to understand.

=)

    
15.10.2015 / 15:46