How to read a certain number of lines in C?

Asked

Viewed 137 times

0

This is my code that reads and searches a certain 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?

  • Edit the question and put the code you’ve already done to make it easier for us to understand your problem.

  • What does this have to do with thread?

  • In this context it does not have much to do, but can be applied to a multithreaded environment

  • As tags should be used to identify your problem, not to say what you will one day do with it.

  • 2

    for(i=0; i<1000; i++){ lerlinha() } ?

1 answer

0

Well, to read 1000 lines one must first think of the criticism of the case in which the last you will read does not possess 1000 lines.

Then 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 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 and will stop when the EOF arrives.

I hope I helped, if it is still difficult I suggest you specify a little more the problem so that the community understands.

=)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.