Home > other >  Redirect output of command line to a variable in C
Redirect output of command line to a variable in C

Time:04-07

Is there a way to redirect output of a command line which returns integer as an output to a variable in C?

for example, if the command is "cmd", then is there a way to redirect its output (an integer) and store it in variable in C? I tried using popen and fgets but it seems to be working only with characters. Any suggestions?

CodePudding user response:

It works perfectly fine with popen and fgets:

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

int
main(int argc, char *argv[])
{
    const char *cmd = argc > 1 ? argv[1] : "echo 42";
    char buf[32];
    FILE *fp = popen(cmd, "r");
    if( fp == NULL ){
        perror("popen");
        return 1;
    }
    if( fgets(buf, sizeof buf, fp) == buf ){
        int v = strtol(buf, NULL, 10);
        printf("read: %d\n", v);
    }
    return 0;
}

CodePudding user response:

If you want to convert a character string from the standard input, you could use fgets and then use atoi to convert the input to an integer.

If you want to convert the output of a command, let's say ls and store the output of the command to a variable, you could learn about fork, dup2, pipe, and exec function family.

More about this topic on this tutorial : Capture the output of a child in C. This tutorial also provide an example with popen if you want to keep things "high level".

CodePudding user response:

Here is an even simpler example using popen() and fscanf():

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    FILE *fp = popen("date ' %s'", "r");
    long seconds;
    if (fp == NULL) {
        fprintf(stderr, "popen failed: %s\n", strerror(errno));
        return 1;
    }
    if (fscanf(fp, "%ld", &seconds) == 1) {
        printf("epoch seconds: %ld\n", seconds);
        pclose(fp);
        return 0;
    } else {
        fprintf(stderr, "invalid program output\n");
        pclose(fp);
        return 1;
    }
}
  • Related