Count the Number of Lines in a File in C

Introduction

In this post, I am going to write a c program to count the number of lines in a file. Here, a file means a text file.

Also Read: Switch Case in C Program to Calculate Area of Circle and Triangle

This is a file handling program in c. In this program, we will open a file in reading mode. Now, the question is how can we count the number of lines in a file?

The answer is so simple. When we encounter an enter key then we can say the line is terminated. In this program, we have to count the enter key or newline character or ‘\n’ with the end of the file. Because at the end of the file, there is no newline character.

Also Read: C Program to Print Multiples of 5 using do-while loop

Just see the following input file that we have to read for counting the number of lines.

Input File: abc.txt

Hello Dear Friends,
Welcome to HPlus Academy.
Thanks for reading this article.
It will definetely help you.

In the above, there are four lines. So our program will show the following output.

count the number of lines in a file
Output: Count the Number of Lines in a File

Now, we will see the actual program.

C Program to Count the Number of Lines in a File

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp;
    char ch;
    int lines;
    fp=fopen("abc.txt","r");
    if(fp==NULL)
    {
        printf("Error while opening a file");
        return -1;
    }
    printf("The contents of the file are:\n\n");
    while((ch=fgetc(fp))!=EOF)
    {
        putchar(ch);
        if(ch=='\n')
        {
            lines++;
        }
    }
    fclose(fp);
    printf("\n\nNumber of lines in a file are %d",lines+1);
    return 0;
}

I hope you have understood this program. If you have any difficulty, then feel free to contact me.

Thank you.

Some Important C Programs

  1. Program in C to Find Longest Line in a File
  2. Palindrome in C using Pointers
  3. Insert and Delete element in Array in C using switch case
  4. C Program to Add Alternate Elements of a 2D Array
  5. Arrays in C for Complete Beginners
  6. C Program to Find Area of a Circle using Preprocessor
  7. Program in C to Remove White Spaces and Comments from a File
  8. C Program to Print Numbers Except Multiples of n
  9. Reverse a Number using getchar and putchar function in c
  10. The while loop in C Programming

Leave a Comment