【问题标题】:How to get the output of grep in C [duplicate]如何在C中获取grep的输出[重复]
【发布时间】:2015-06-16 01:16:59
【问题描述】:

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

【问题讨论】:

  • @myaut 不是重复的,因为 C 不是 C++。
  • @Jens:差别很小,OP 需要的是popen()(这是那里的第一个答案)。

标签: c grep


【解决方案1】:

如果您想继续使用execl,可以使用pipe

有一些例子和教程here

【讨论】:

    【解决方案2】:

    你可以使用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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2022-12-12
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      相关资源
      最近更新 更多