Q:

C program to find number of lines in a file

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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
	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=fgetc(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: 2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to create a text file using file handlin... >>