如何在C中获取grep的输出

Ped*_*osa 0 c grep

我在我的 C 代码中使用函数 execl() 执行 grep 命令,并且我想在我的 C 程序中使用这个命令的输出。我该怎么做?

Dav*_*eri 5

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)