Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my linecount in C work?

Tags:

c

line-count

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?

like image 571
Steffen Avatar asked Dec 01 '22 22:12

Steffen


2 Answers

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

{
    count++;
}
like image 112
md5 Avatar answered Dec 07 '22 23:12

md5


Change

if (ch == '\n'); 

to:

if (ch == '\n')
like image 25
ScoPi Avatar answered Dec 07 '22 23:12

ScoPi