Program to count number of lines in a file.

28 Dec 2022 Balmiki Kumar 0 C Programming

C Program to Count the Number of Lines in a File

A C program to count the number of lines in a file is a program written in the C programming language that counts the number of lines in a text file. The program reads the file character by character and counts the number of newline characters to determine the number of lines in the file. This program is useful for tasks such as analyzing log files, processing large datasets, and working with text files.

Program: Program to count number of lines in a file.

#include
int main()
/* Ask for a filename and count number of lines in the file*/
{
 //a pointer to a FILE structure
 FILE *fp;
 int no_lines = 0;
 //consider 40 character string to store filename
 char filename[40], sample_chr;
 //asks user for file name
 printf("Enter file name: ");
 //receives file name from user and stores in a string named 'filename'
 scanf("%s", filename);
 //open file in read mode
 fp = fopen(filename, "r");
 //get character from file and store in sample_chr
 sample_chr = getc(fp);
 while (sample_chr != EOF) {
 //Count whenever sample_chr is '\n'(new line) is encountered
 if (sample_chr == '\n')
 {
 //increment variable 'no_lines' by 1
 no_lines=no_lines+1;
 }
 //take next character from file.
 sample_chr = getc(fp);
 }
 fclose(fp); //close file.
 printf("There are %d lines in %s \n", no_lines, filename);
 return 0;
}

Output:

Enter file name:abc.txt
There are 4 lines in abc.txt

Attention: In this program, name of the file to be read is taken as input. A file by the given name is opened in read-mode using a File pointer 'fp'. Characters from the file are read into a char variable 'sample_chr' with the help of getc function. If a new line character('\n') is encountered, the integer variable 'no_lines' is incremented. character read into 'sample_char' is not a new line character, next character is read from the file. This process is continued until the last character of the file(EOF) is encountered. The file pointer is then closed and the total number of lines is shown as output.

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.