Store output of system command to local char array in c

Is there a way to save the output of the system command to a char array since the system command only returns int.

+3


source to share


1 answer


Unable to receive output system(3)

. Well, you can redirect the output of any command to a file and then open and read that file, but a smarter approach is to use popen(3)

.

popen(3)

replaces system(3)

and allows you to read the output of a command (or, depending on the flags you pass, you can write to the input of the 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;
}

      

+2


source







All Articles