Sunday, 24 August 2014

Filled Under:

C Program to Find the Number of Lines in a Text File

Share
Here is simple C program to find the number of lines in a text file.It takes the name of file from user and display the number of lines contains in that file,if file is exist in system.

C Program to Find the Number of Lines in a Text File


C Program to Find the Number of Lines in a Text File



#include <stdio.h>
 
int main()
{
    FILE *fileptr;
int count_lines = 0;
char filechar[40], chr;
 
printf("Enter file name: ");
scanf("%s", filechar);
    fileptr = fopen(filechar, "r");
//extract character from file and store in chr
    chr = getc(fileptr);
while (chr != EOF)
{
//Count whenever new line is encountered
if (chr == 'n')
{
            count_lines = count_lines + 1;
}
//take next character from file.
        chr = getc(fileptr);
}
fclose(fileptr); //close file.
printf("There are %d lines in %s in a file\n", count_lines, filechar);
return 0;
}

Output

Enter file name:data.txt
There are 5 lines in data.txt in a file