Counting number of lines in the file in C

caddy-caddy picture caddy-caddy · Apr 20, 2015 · Viewed 10.8k times · Source

I'm writing a function that reads the number of lines in the given line. Some text files may not end with a newline character.

int line_count(const char *filename)
{
   int ch = 0;
   int count = 0;    
   FILE *fileHandle;

   if ((fileHandle = fopen(filename, "r")) == NULL) {
      return -1;
   }

   do {
      ch = fgetc(fileHandle);
      if ( ch == '\n')
         count++;
   } while (ch != EOF);

   fclose(fileHandle);

   return count;
}

Now the function doesn't count the number of lines correctly, but I can't figure out where the problem is. I would be really grateful for your help.

Answer

pens-fan-69 picture pens-fan-69 · Apr 20, 2015

Here is another option (other than keeping track of last character before EOF).

int ch;
int charsOnCurrentLine = 0;

while ((ch = fgetc(fileHandle)) != EOF) {
    if (ch == '\n') {
        count++;
        charsOnCurrentLine = 0;
    } else {
        charsOnCurrentLine++;
    }
}
if (charsOnCurrentLine > 0) {
    count++;
}