Result of a command in a variable

Asked

Viewed 69 times

0

When I run the following code it stores the output status of the command wc -l which has value 0 as it has been successfully executed.

#include <stdio.h>
#include <stdlib.h>

int main() {

    int status = system("echo 'hello world' | wc -l");
    printf("%d", status);

    return 0;
}

But what I need is the result value of this command, which in this case became 1. How do I store this result in a variable in C??

1 answer

1

You can use the function popen() who invokes the shell and returns a type structure FILE*. To do this just specify the command and the type that is for reading "r" in this case.

An illustrative example:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *fp;
    int status;
    char conteudo[200]; //define o tamanho do buffer aqui

    fp = popen("echo \"Hello Word\" | wc -l", "r");
    if (fp == NULL) {
        printf("Error\n");
        return EXIT_FAILURE; //Manipule os erros
    }

    while (fgets(conteudo, 200, fp) != NULL) 
        printf("%s\n", conteudo);

    status = pclose(fp);
    if (status == -1) {
        printf("Error\n");
        return EXIT_FAILURE; //Manipule os erros
    }
    else {
        //aqui pode determinar se houve sucesso ou uma falha na execucao do comando.
    }

    return EXIT_SUCCESS;
}

Exit:

1

More information on the popen function, or refer to the typing manual man popen in the terminal.

  • That helps me a lot! But I still have a question... how do I isolate this code in a function that receives a string from a command and returns a result?

Browser other questions tagged

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