3

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

3
  • 1
    The int isn´t the output, but the exit value. ... Look into piping. Commented Aug 2, 2015 at 18:29
  • Please edit your question with the platform that you are using. The task you need to perform may be more efficient with platform specific functionality. Commented Aug 2, 2015 at 20:07
  • Which language? In C++, the preferred data structure for text is std::string which is not available in C. Remember in C, there is a lot of effort in dynamic text processing, because you need to have a dynamically allocated array of characters. In C++, the std::string class handles this for you. So, choose your tags wisely. Commented Aug 2, 2015 at 20:09

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.