Question

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?

Was it helpful?

Solution

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

{
    count++;
}

OTHER TIPS

Change

if (ch == '\n'); 

to:

if (ch == '\n')

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).

you have trailing semicolon to delete after if

and for reading files, better use this code :

while((fgets(blahblahblah)) != NULL) {
  counter++;
}

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

if (ch == '\n')

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.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top