In this tutorial, we will write a C Program to find the number of lines in a text file. Before that, you may go through the following C topics.
Explanation: The program asks the user to enter the file name or file path (if not present in the same directory). If the file is not present then it will throw a message else it will continue the counting process.
First, the file checks if the starting is EOF or not, if not then the count will increase to 1 (if this part is not checked then the count will show one less result than the actual number of lines present), and then the counting begins using a while loop. And it increases the count when a newline is found every time inside a file.
C Program to Count the Number of Lines in a File
Source code: Count the number of lines in a file in C
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 31 32 33 34 35 36 37 38 39 40 | #include <stdio.h> #define FILE_NAME_SIZE 100 int main() { FILE * fptr; int count = 0; char fileName[FILE_NAME_SIZE], ch; printf("Enter the name of the file: "); scanf("%s", fileName); // Opening the file and check for its existence fptr = fopen(fileName, "r"); if (fptr == NULL) { printf("Could not open file."); return 0; } ch = getc(fptr); //if file is not empty then count the first line as 1 if (ch != EOF) count++; // extracting the lines while (ch != EOF) { // if character id newline if (ch == '\n' || ch == '\0') count = count + 1; ch = getc(fptr); } fclose(fptr); printf("Number of line present in %s: %d ", fileName, count); return 0; } |
Output:
The content inside the test.txt:
Hello!
This is simple2code.com
You can learn coding tutorials and programs from the beginning.