Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the system command output in a variable?

Tags:

c++

c

unix

system

I am executing a system() function which returns me a file name. Now I dont want to display the output on the screen(ie the filename) or pipe to a newfile. I just want to store it in a variable. is that possible? if so, how? thanks

like image 927
IITian Avatar asked May 07 '11 07:05

IITian


People also ask

What can be used to store the output of another command?

We can use the redirections operators to save the output of commands into files. Redirection operators redirect the output of a command to the file instead of the output terminal.

How do you store the output of a command to a variable in Perl?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout: my $pid = 5892; my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`; print "not = $var\n"; This should do it.


1 Answers

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.

like image 177
nitin Avatar answered Oct 04 '22 22:10

nitin