Skip to content
Advertisement

How to grep a string in a program?

#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?

Advertisement

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.

Advertisement