1

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?

qwerty
  • 85
  • 2
  • 6

3 Answers3

3

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;
}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • May be worth a note to "adjust `buf` size as needed". (apparent to the experienced, but may not be immediately so to new user that enters `cat some/long/hairy/path.../../..file_w_int.txt`) – David C. Rankin Apr 06 '22 at 19:37
  • You could even use `fscanf()` for this and get rid of the buffer :) – chqrlie Apr 06 '22 at 19:52
0

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".

0

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;
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189