如何在 C 中获取 grep 的输出

  • 本文关键字:grep 输出 获取 c grep
  • 更新时间 :
  • 英文 :


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

您可以使用

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;
}

如果你想继续使用 execl ,你可以使用管道。

这里有一些示例和教程。

最新更新