Is there any way to store output of system command into char array, since system command is returning only int.
1 Answer
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;
}
std::stringwhich 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++, thestd::stringclass handles this for you. So, choose your tags wisely.