Search code examples
cline-count

Why doesn't my linecount in C work?


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?


Solution

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

    {
        count++;
    }