In this program, we are going to share c program to find the number of lines in a text file. If you are a beginner and want to start learning the c programming, then keep your close attention in this tutorial as I am going to share a c program to find the number of lines in a text file.
Copy the below C program and execute it with the help of C compiler.
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 *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; } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.