How can i grep a file using c++..?

I have a file. File having a keyword. i want to get the count of that.

i am tring to do
int count ;
count = system("grep -c keyword file1.txt");
cout << count ; /// this is giving me system command return value not the actual output..


how can i ghet the actual output in c++?


jujose

How can i grep a file using c++..?

I have a file. File having a keyword. i want to get the count of that.

i am tring to do
int count ;
count = system("grep -c keyword file1.txt");
cout << count ; /// this is giving me system command return value not the actual output..


how can i ghet the actual output in c++?


jujose

i think you could system("grep -c keyword file1.txt > myfile");
and then read myfile for the output.

Or you could just simply open the file in your program, read each line, search for the keyword then increment a counter when found. A pretty simple program to write if you already know file i/o functions. If you don't then this is a good opportunity to expand your knowledge of C++ standard classes.

Or you could just simply open the file in your program, read each line, search for the keyword then increment a counter when found. A pretty simple program to write if you already know file i/o functions. If you don't then this is a good opportunity to expand your knowledge of C++ standard classes.

Thanks..
I too thought of this solution but it loooks ugly to me.. anybody know any simple way to slove this issue

Like I said, its a simple function. You might want to enhance it to check if the keyword appears multiple times on the same line.

int grep(std::string& filename, std::string keyword)
{
    int counter = 0;
    std::string line;
    ifstream in(filename.c_str());
    if( in.is_open())
    {
          while( getline(in,line) )
          {
              if( line.find(keyword) )
                   counter++;
          }
    }
    return counter;
}
This article has been dead for over six months. Start a new discussion instead.