Ferrari Service
Ferrari Service

Reputation: 79

How to save the system(cmd) result in a variable?

I've the function system(cmd) that executes a command which returns two numbers to the terminal:

977190
977190

How can I assign one of these numbers to a variable to use in the program? It doesn't matter if it is a char or an int variable.

Upvotes: 0

Views: 111

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

If posix is an option, you can switch from system to popen

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

FILE *popen(const char *, const char *);
int pclose(FILE *);

int main(void)
{
    FILE *cmd;

    cmd = popen("echo 123", "r");
    if (cmd == NULL)
    {
        perror("popen");
        exit(EXIT_FAILURE);
    }

    char result[1024];    
    long number = 0;

    if (fgets(result, sizeof(result), cmd))
    {
        number = strtol(result, NULL, 10);
    }
    pclose(cmd);
    printf("%ld\n", number);
    return 0;
}

Output:

123

Upvotes: 2

Related Questions