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

1

In the class of files, the teacher used " EOF " to determine if the file had reached its end, but reading the FEOF ", does the two terminologies work?

I tried to implement the algorithm that came with this here or this to perform the row count of a file txt, but it caused several errors in the issue of using "FEOf" (and its comparison with the file read) and it turned out that I did this gambiarra:

#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 succinct explanation about the implementation of the aforementioned link's above, or explain if and how to make the gambiarra above stop being a gambiara without having to add " 1 "to generate the right result and without the vector being static, ie making the item with pointer being the exact size of the content file?

    
asked by anonymous 26.11.2016 / 01:52

1 answer

2

An easier way is to use the return function of the fread itself, when returning 0 means that the file has finished (and in C it's like false). Then your code gets + - 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.

    
26.11.2016 / 02:17