0

I'm executing grep command in my C code with the function execl(), and I want to use the output of this command in my C program. How do I do it?

Pedro Romano Barbosa
  • 563
  • 2
  • 10
  • 27

2 Answers2

5

You can use popen:

#include <stdio.h>
#include <stdlib.h>

FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);

int main(void)
{
    FILE *cmd;
    char result[1024];

    cmd = popen("grep bar /usr/share/dict/words", "r");
    if (cmd == NULL) {
        perror("popen");
        exit(EXIT_FAILURE);
    }
    while (fgets(result, sizeof(result), cmd)) {
        printf("%s", result);
    }
    pclose(cmd);
    return 0;
}
David Ranieri
  • 37,819
  • 6
  • 48
  • 88
1

If you want to keep using execl, you can use a pipe.

There is some examples and tutorials here.

Aracthor
  • 5,527
  • 6
  • 30
  • 56