C program to find number of lines in a file

In this program, we are going to learn how to find total number of lines available in a text file using C program?

This program will open a file and read file’s content character by character and finally return the total number lines in the file. To count the number of lines we will check the available Newline (\n) characters.

File "test.text"

Hello friends, how are you?
This is a sample file to get line numbers from the file.

Program to get/find total number of lines in a file in C

#include <stdio.h>

#define FILENAME "test.txt"

int main()
	FILE *fp;
	char ch;
	int linesCount=0;
	//open file in read more
		printf("File \"%s\" does not exist!!!\n",FILENAME);
		return -1;

	//read character by character and check for new line	
	//close the file
	//print number of lines
	printf("Total number of lines are: %d\n",linesCount);
	return 0;	


Total number of lines are: 2

C File Handling Programs »

Related Programs


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.