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.
- Declaring the variables.
- Using control statements.
- 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();
}