How to grep a string in a program?

1.7k views Asked by At
#include <stdlib.h>

int foo(char *str_buf_to_grep)
{
    // How to write the following line correctly?
    return system("??? str_buf_to_grep ??? | grep mykeyword"); 
}

Description:

  1. The str_buf_to_grep is given in any way, which might be the content of a text file, and might be very long and complex, even contains special characters, such as |, ", etc.

  2. I want to use the grep command to find matched lines, and the patterns might be very complex.

How should I implement it?

2

There are 2 answers

0
Rafael Baptista On BEST ANSWER

Use popen:

FILE* file = popen( "grep mykeyword", "r" );
fwrite( str_to_grep, 1, strlen( str_to_grep ), file );
pclose( file );

The echo example by Matt might not work as expected if the string has quotes or similar character interpreted specially by the shell.

I assume your example with grep is just for purposes of asking the question - because like Matt said, it would in all ways be better and faster to look for substrings yourself with a strstr loop or similar.

3
quarterdome On

Technically, what you are looking for is this:

char cmd[1024];
sprintf(cmd, "echo '%s' | grep mykeyword", str_to_grep);
return system(cmd);

This won't work if your str_to_grep includes single quotes (') in it. You would need to replace single quotes with slash+quote (\') in order to avoid shell interpolation.

However, I can't understand why would you want to shell out to grep command, rather than use strstr() function, like this:

strstr(str_to_grep, "mykeyword");

The latter is always more efficient, less typing, more portable, and less error prone.