C Program to Count Number of Lines in a Text File

In this tutorial you will learn about the C Program to Count Number of Lines in a Text File and its application with practical example.

In this tutorial, we will learn to create c program to Count Number of Lines in a Text File. The file must exist in the directory where the executable file of this program is present.

Prerequisites

Before starting with this tutorial we assume that you are best aware of the following C programming topics: C Pointers, C File Handling, C Strings and C Input Output.

Create required files

Let’s first create files (inside the current project directory) as following:

  • f1.txt – file to count line

The file must be saved in the folder where you are saving program file. Put the following content in corresponding file:

f1.txt

How to Count Number of Lines In Text file?

In this C program we will count number of lines in file (f1.txt). The number of lines in a file can be find by counting the number of new line characters present.

C Program to Count Number of Lines in a Text File

In this program we will count number of lines in a text file. We would first declared and initialized the required variables. Next, we would prompt user to input source file names(f1.txt) . Later in the program we will count number of lines present in file (f1.txt). Finally, we will display the number of lines in text file using printf statement.

Output:-

C-Program-to-Count-Number-of-Lines-in-a-Text-File

In the above program, we have first declared and initialized a set variables required in the program.

  • *fptr= file pointer
  • fname= to hold source file name
  • lcount = number of lines, initialized with 0
  • chr = to extract character

Now, user needs to provide the source file name. We will assign it to variable ‘fname’. Next, we will try to count number of lines in file. Next, we will extract and loop through individual character from file until we reach EOF(end of file). We will count the number of new line characters present in the file and increase the lcount. Finally, we will display the number of lines in text file using printf statement.

In this tutorial we have learn about the C Program to Count Number of Lines in a Text File and its application with practical example. I hope you will like this tutorial.