by Dinesh Thakur

In this program user ask to count the line in a file. User declares the required variable for storing the value and some are of pointer type. User put the method for opening file and using if-else condition to vary the condition if content is not found then terminate else with the use of while condition read the content until (ch != EOF). Then varying the condition the counted lines are on the display on the screen. In the end a method in end to close the file.

Problem Statement:

This is C Program to count out the lines on a file.

  1. Declaring the variables.
  2. Using control statements.
  3. Display result on the screen.

Here is C source code for counting the lines on a file. The output of this program shown below. 

#include<stdio.h>

void main()
{
     FILE *p;
     char ch;
     int l=1;
     clrscr();
     p=fopen("source","r");
     if(p==NULL)
         {
               printf("File not Found");
         }
        else
         {
               ch=fgetc(p);
               while(ch!=EOF)
                      {
                          printf("%c",ch);
                          if(ch=='\n')
                           {
                                l++;
                           }
                                ch=fgetc(p);
                     }
                                printf("Lines in a file are= %d",l);
         }
                                fclose(p);
                                getch();

Count the Lines in a File