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 c and c++, 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;}
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.