Satadru Bag Satadru Bag - 2 months ago 12
Bash Question

Executing line counting bash command (wc -l) inside a c++ program

I want to calculate the no of lines of data file before declaring a global array. I know in terminal if I execute

wc -l filename
, I get the number of lines. How do I use that command
(wc -l filename)
and store its result into a int type variable inside a c++ program? When I use the following code:
int NT=system(" wc -l file.d");

I get
NT=0.


How to get the no. of lines in file.d in NT?

Answer

One way you can get the number of lines in a file is by using getline:

#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    fstream in("file.d");
    int lines = 0;
    string s;
    while (getline(in, s))
    {
        ++lines;
    }
    cout << lines << endl;
    return 0;
}

EDIT...

A more efficient way (if you only want the count and don't want to use any of the data) is to use istream::ignore, as pointed out by Matteo Italia.

#include <fstream>
#include <iostream>
#include <limits>
using namespace std;

int main()
{
    fstream in("in.txt");
    int lines = 0;
    char endline_char = '\n';
    while (in.ignore(numeric_limits<streamsize>::max(), in.widen(endline_char)))
    {
        ++lines;
    }
    cout << lines << endl;
    return 0;
}

Either way will output the number of lines in a file called "file.d". You can compare its output to that of 'wc -l'.

Comments