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
  • 587
  • 3
  • 11
  • 29

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
  • 39,972
  • 7
  • 52
  • 94
1

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

There is some examples and tutorials here.

Aracthor
  • 5,757
  • 6
  • 31
  • 59