如何在C中获取grep的输出

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

你可以使用popen

 #include  #include  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 ,可以使用管道 。

这里有一些示例和教程。