如何在C中获取grep的输出 [英] How to get the output of grep in C
本文介绍了如何在C中获取grep的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的 C 代码中使用函数 execl() 执行 grep 命令,并且我想在我的 C 程序中使用这个命令的输出.我该怎么做?
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?
推荐答案
你可以使用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;
}
这篇关于如何在C中获取grep的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文