Ashutosh
Ashutosh

Reputation: 481

Store output of system command into local char array in c

Is there any way to store output of system command into char array, since system command is returning only int.

Upvotes: 3

Views: 2731

Answers (1)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

There's no way to retrieve the output of system(3). Well, you could redirect the output of whatever command is executed to a file and then open and read that file, but a more sane approach is to use popen(3).

popen(3) replaces system(3) and it allows you to read the output of a command (or, depending on the flags you pass it, you can write to the input of a command).

Here's an example that executes ls(1) and prints the result:

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

int main(void) {
    FILE *ls_cmd = popen("ls -l", "r");
    if (ls_cmd == NULL) {
        fprintf(stderr, "popen(3) error");
        exit(EXIT_FAILURE);
    }

    static char buff[1024];
    size_t n;

    while ((n = fread(buff, 1, sizeof(buff)-1, ls_cmd)) > 0) {
        buff[n] = '\0';
        printf("%s", buff);
    }

    if (pclose(ls_cmd) < 0)
        perror("pclose(3) error");

    return 0;
}

Upvotes: 2

Related Questions