Thursday, December 13

Program to count number of lines in a file


Write a program to find the number of lines in a text file.

Number of lines in a file can be determined by counting the number of new line characters present.

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

#include <stdio.h>
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

Explanation:
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. If the
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.