Count number of lines in the file

Asked

Viewed 332 times

1

Good morning,this function counts the number of lines of a file,but it has a little problem,it only counts the line when it finds the n,for example to test it,I would create a text file,and write a word to see if it was ok,And then I went to find out that it didn’t count because I hadn’t entered at the end of the word and so she couldn’t find the number,can someone else tell me how to count the number without having to worry about giving a word a enter? Function code:

char numerolinhas(){
    char contar;
    int linhas=0;
    FILE *file;

    file=fopen("Frutas forca.txt","r");

    char conta;
    while((conta=fgetc(file))!=EOF){
        if(conta=='\n'){
        linhas++;
        }
    }
    fclose(file);

    return linhas;

1 answer

1

Your problem is the definition of "line".

Normally a line is defined by "a sequence of (0 or more) characters terminated by, and including, one end-of-the-line".

In some cases it can also be defined by "a sequence of (0 or more) characters separated by a end-of-the-line (or EOF) not belonging to the line".

In the first case the end-of-line is part of the line, in the second case not.

Your program uses the first line definition, but the file you use was created with the second definition.

Solution 1) changes the file to meet the line definition used by the program

Solution 2) changes the program to accept the second line definition.


An empty file (0 bytes) how many lines it has?
definition 1) 0 lines; definition 2) 1 line (empty)

A file with an X (1 byte) how many lines it has?
definition 1) 0 lines (1 "loose" character); definition 2) 1 line (with "X")

A file with a ENTER (1 byte) how many lines it has?
definition 1) 1 line (empty, ie only with ENTER); definition 2) 2 lines

  • Thank you, but could you write the code the way you explained it? I can’t apply it to the code.With the code I can actually learn it.

  • So it’s easy. With the definition of lines you want to use, just add 1 the number of lines of the other definition... return linhas + 1;

  • I believe that this sum would only apply if the last character is not a ' n'. When arriving at the EOF, this is after the end of the loop, test whether or not the last character read is a ' n' and add 1 if it is not.

  • Ah!... and as @anonimo says, there is still a third (conditional) possible definition for line :)

  • Thanks for the suggestions,.

Browser other questions tagged

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