execute grep command in C language and return result

Asked

Viewed 104 times

-2

void main()
{
    char comando[2000];
    char resultado[500]
    sprintf(comando, "grep '[0-9]{50}-' input.txt);
    resultado = system(comando);

    printf("%s\n",resultado);
}

I only need 1 match, and return the value as a result, the above code does not compile, it’s just an example of how I’d like it to look.

  • It’s just an example of how I’d like it to work, what I can’t get is the return of the grep command, until the sprintf part I think is correct

  • You should provide a functional example that reproduces the problem. https://answall.com/help/mcve

  • I’m sorry Gabriel, but if it was functional I wouldn’t be asking. I made a prototype of how I’d like it to be, to try to explain the problem. I cannot get a result of the system() flame if there is another way or other to do this would be very grateful.

1 answer

0

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

That’s exactly what I was looking for. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.