How to store the system command output in a variable? How to store the system command output in a variable? unix unix

How to store the system command output in a variable?


A single filename? Yes. That is certainly possible, but not using system().

Use popen(). This is available in and , you've tagged your question with both but are probably going to code in one or the other.

Here's an example in C:

#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){    FILE *fpipe;    char *command = "ls";    char c = 0;    if (0 == (fpipe = (FILE*)popen(command, "r")))    {        perror("popen() failed.");        exit(EXIT_FAILURE);    }    while (fread(&c, sizeof c, 1, fpipe))    {        printf("%c", c);    }    pclose(fpipe);    return EXIT_SUCCESS;}


You can use popen(3) and read from that file.

FILE *popen(const char *command, const char *type);

So basically you run your command and then read from the FILE returned. popen(3) works just like system (invokes the shell) so you should be able to run anything with it.


Well,There is one more easy way by which you can store command output in a file which is called redirection method. I think redirection is quite easy and It will be useful in your case.

so For Example this is my code in c++

#include <iostream>#include <cstdlib>#include <string>using namespace std;int main(){   system("ls -l >> a.text");  return 0;}

Here redirection sign easily redirect all output of that command into a.text file.