Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Get Total File Line Number

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
like image 292
NewFile Avatar asked Oct 02 '13 15:10

NewFile


People also ask

How do I count the number of lines in a file?

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.

How do I count the number of lines in a file in Terminal?

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.

How does EOF work in C?

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.


1 Answers

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');
like image 199
P0W Avatar answered Sep 23 '22 20:09

P0W