Michael_19 Michael_19 - 3 months ago 21
C Question

C function that counts lines in file

When I try to run my program, I get the wrong number of lines printed.

LINES: 0


This is the output although I have five lines in my .txt file

Here is my program:

#include<stdio.h>
#include<stdlib.h>

int countlines(char *filename);

void main(int argc, char *argv[])
{
printf("LINES: %d\n",countlines(argv[1]));
}


int countlines(char *filename)
{
// count the number of lines in the file called filename
FILE *fp = fopen(filename,"r");
int ch=0;
int lines=0;

if (fp == NULL);
return 0;

lines++;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
lines++;
}
fclose(fp);
return lines;
}


I am sure it is a simple mistake but I am new to programming. Any help would be greatly appreciated.

Answer
while(!feof(fp))
{
  ch = fgetc(fp);
  if(ch == '\n')
  {
    lines++;
  }
}

But please note: Why is “while ( !feof (file) )” always wrong?.