Is there a function I can use to get total file line number in C++
, or does it have to be manually done by for
loop?
#include <iostream>
#include <ifstream>
ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?
}
text.txt
line1
line2
line3
The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.
Using “wc -l” There are several ways to count lines in a file. 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.
The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.
I'd do like this :
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
++lines_count;
Or simply,
#include<algorithm>
#include<iterator>
//...
lines_count=std::count(std::istreambuf_iterator<char>(aFile),
std::istreambuf_iterator<char>(), '\n');
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