Count the lines of a txt file in c / c++

Asked

Viewed 8,939 times

1

In file class the teacher used " EOF " to determine whether the file had reached its end, but by reading the wiki about c files, I saw that the implementation of the end check of a file is " FEOF ", the two terminologies work ?

I tried to implement the algorithm that looked like this here or this to count lines of a txt file, but it generated several errors in the issue of using " Feof " ( and its comparison with the read file ) and I ended up doing this trick:

#include <stdio.h>

#include <string.h>

int main () {

    FILE *arq;

    char text[200], letra = '\n';

    int vezes;

    arq = fopen("teste.txt","r");

        fread (&text, sizeof(char), 200, arq);

        for (int i = 0; i < strlen(text); i++){

            if(text[i] == letra){

                vezes++;

            }
        }

    printf("\nLinhas: %i\n",vezes + 1);

    fclose(arq);

}

Could you give a brief explanation regarding the implementation of the links already mentioned above, or me explain if and how to do the above gambiarra stop being a " gambiara " without I have to add " +1 " to generate the right result and without the vector being static, ie do such item with pointer being the exact size of the contents file ?

  • 2

    Question Related to EOF vs FEOF: http://stackoverflow.com/questions/36164718/confusion-with-eof-vs-feof

1 answer

3


An easier way is to use the fread function return itself, when returning 0 means that the file is finished (and in C it is as if it were false). So your code is +- like this:

#include <stdio.h>

#include <string.h>

int main () {

    FILE *arq;

    char c, letra = '\n';

    int vezes;

    arq = fopen("teste.txt","r");

        //Lendo o arquivo 1 por 1
        while(fread (&c, sizeof(char), 1, arq)) {
            if(c == letra) {
                vezes++;
            }
        } 

    printf("\nLinhas: %i\n",vezes + 1);

    fclose(arq);

}

I know that’s not exactly your question, but it’s a way to solve your problem without worrying about EOF.

Browser other questions tagged

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