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?
You have a trailing semicolon ; after your if statement. Then, the block is always executed:
{
    count++;
}
                        Change
if (ch == '\n'); 
to:
if (ch == '\n')
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With