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?
Asked
Active
Viewed 1.3k times
0
-
@myaut Not a duplicate, since C is not C++. – Jens Apr 10 '15 at 10:52
-
1@Jens: the difference is small, what OP needs is `popen()` (and that it is first answer there). – myaut Apr 10 '15 at 11:00
2 Answers
5
You can use 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;
}

David Ranieri
- 39,972
- 7
- 52
- 94