# Write a C program to find total number of lines in an existing file

CServer Side ProgrammingProgramming

Open a file in reading mode. If the file exists, then write a code to count the number of lines in a file. If the file does not exist, it displays an error that the file is not there.

The file is a collection of records (or) It is a place on the hard disk where data is stored permanently.

Following are the operations performed on files −

• Naming the file

• Opening the file

• Writing into the file

• Closing the file

## Syntax

Following is the syntax for opening and naming a file −

1) FILE *File pointer;
Eg : FILE * fptr;
2) File pointer = fopen ("File name", "mode");
Eg : fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");

## Program 1

#include <stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
}

## Output

Total number of lines are: 3
Note: employee details.txt file consist of
Pinky
20
5000.000000
Here total number of line are 3

## Program 2

In this program, we will see how to find a total number of lines in a file that does not exist in the folder.

#include <stdio.h>
#define FILENAME "sample.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in write mode
fp=fopen(FILENAME,"w");
printf ("enter text press ctrl+z of the end");
while ((ch = getchar( ))!=EOF){
fputc(ch, fp);
}
fclose(fp);
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
}

## Output

enter text press ctrl+z of the end
Hi welcome to Tutorials Point
Total number of lines are: 2