can someone show me how to get the total number of lines in a text file in programming language C?
But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output. 1. The “wc -l” command when run on this file, outputs the line count along with the filename.
Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.
If you are in *Nix system, you can call the command wc -l that gives the number of lines in file.
This is one approach:
FILE* myfile = fopen("test.txt", "r");
int ch, number_of_lines = 0;
do
{
ch = fgetc(myfile);
if(ch == '\n')
number_of_lines++;
} while (ch != EOF);
// last line doesn't end with a new line!
// but there has to be a line at least before the last line
if(ch != '\n' && number_of_lines != 0)
number_of_lines++;
fclose(myfile);
printf("number of lines in test.txt = %d", number_of_lines);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With