4

I'm trying to read a text file but before that I want to know how many elements I'm going to read. So I need to count the lines of a text file. So far, I have this:

int getLinecount (char *file) 
{
    int ch, count = 0;
    FILE *fp = fopen(file, "r");
    if(fp == NULL)
    {
        return -1;
    }
    while((ch = fgetc(fp)) != EOF)
    {
        if (ch == '\n'); 
        {
            count++;
        }
    }
    fclose(fp);
    return count;
}

This worked pretty fine. I have changed nothing about the text file and still it prints 130,000 though the file only has 10,000 lines. The only thing I wrote in my main is:

linecount = getLinecount("...");

I am really curious where the error is. Also, is there a better option of getting the linecount?

Steffen
  • 3,999
  • 1
  • 23
  • 30
  • Tracing this through using a debugger would have pointed you to this `;` immediately. – alk Nov 08 '12 at 15:03
  • Learn your compiler & compile with full warnings on. For example gcc's `-Wextra` option catches that & outputs: `warning: empty body in an if-statement` – Eugen Constantin Dinca Nov 08 '12 at 16:12

7 Answers7

10

You have a trailing semicolon ; after your if statement. Then, the block is always executed:

{
    count++;
}
md5
  • 23,373
  • 3
  • 44
  • 93
4

Change

if (ch == '\n'); 

to:

if (ch == '\n')
ScoPi
  • 1,193
  • 9
  • 14
3

Trailing semi-colon after the if: remove it. With the trailing semi-colon the code is equivalent to:

if (ch == '\n') {}
count++;

meaning that count is incremented for every iteration of the loop (every char in the file).

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

you have trailing semicolon to delete after if

and for reading files, better use this code :

while((fgets(blahblahblah)) != NULL) {
  counter++;
}
doniyor
  • 36,596
  • 57
  • 175
  • 260
1

Everything is fine except for a semicolon (;), which should be removed from the line

if (ch == '\n')
Chris
  • 44,602
  • 16
  • 137
  • 156
Mohit Sehgal
  • 825
  • 1
  • 9
  • 26
0

Apart from the ; issue mentioned by others, an alternative solution can be found in this post as he explains why he does things the way he does.

Community
  • 1
  • 1
Jensen
  • 3,498
  • 2
  • 26
  • 43
0

You might want to consider the OS you are using to create and view this file.

Copied from PHP Echo Line Breaks:

  • '\n' is a linux/unix line break
  • '\r' is a classic mac line break [OS X uses the above unix \n]
  • '\r'+'\n' is a windows line break
Community
  • 1
  • 1
kdmin
  • 434
  • 3
  • 14