In this program, we are going to share how to count the number of lines in a file using c programming language. 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 count the number of lines in a file.
Copy the below c program and execute it with the help of c compiler. At the end of this program, We have shared the output of this program.
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 28 29 30 | #include <stdio.h> #define FILENAME "example.txt" int main() { FILE *fp; char ch; int linesCount=0; fp=fopen(FILENAME,"r"); if(fp==NULL) { printf("File \"%s\" does not exist!!!\n",FILENAME); return -1; } while((ch=fgetc(fp))!=EOF) { if(ch=='\n') linesCount++; } fclose(fp); printf("The total number of lines are: %d\n", linesCount); return 0; } |
The total number of lines are: 10
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.
Article Tags: c - Retrieving total line numbers in a file, C function that counts lines in file, C program to count lines, C program to count number of lines in a file, C Program to Find the Number of Lines in a Text File, Counting number of lines in the file in C, file - C Program to count comment lines (// and /* */)