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
1 2 3 4 5 |
I'm at line 1 I'm at line 2 I'm at line 3 I'm at line 4 I'm at line 5 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <stdio.h> int main() { FILE *fptr; int lcount = 0; char fname[40], chr; clrscr(); printf("Enter file name:"); scanf("%s", fname); fptr = fopen(fname, "r"); chr = getc(fptr); while (chr != EOF) { //Count new line if (chr == 'n') { lcount = lcount + 1; } chr = getc(fptr); } fclose(fptr); //close file. printf("There are %d lines in %s in a file\n", lcount, fname); getch(); return 0; } |
Output:-
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.