In this program, we are going to share a C program to count number of lines in a 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 count number of lines in a file with the output.
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 28 29 30 | #include <stdio.h> #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; char filename[MAX_FILE_NAME]; char c; printf("Enter file name: "); scanf("%s", filename); fp = fopen(filename, "r"); if (fp == NULL) { printf("Could not open file %s", filename); return 0; } for (c = getc(fp); c != EOF; c = getc(fp)) if (c == '\n') count = count + 1; fclose(fp); printf("The file %s has %d lines\n ", filename, count); 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.