Created
April 5, 2016 07:12
-
-
Save meritozh/f0351894a2a4aa92871746bf45879157 to your computer and use it in GitHub Desktop.
use c++ to execute a command and get the output of command. It only grab stdout. Use perror or add "2>&1" for grabbing stderr.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdarg> | |
#include <string> | |
#include <fstream> | |
#include <memory> | |
#include <cstdio> | |
std::string exec(const char* cmd) { | |
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); | |
if (!pipe) return "ERROR"; | |
char buffer[128]; | |
std::string result = ""; | |
while (!feof(pipe.get())) { | |
if (fgets(buffer, 128, pipe.get()) != NULL) | |
result += buffer; | |
} | |
return result; | |
} | |
int main(int argc, char const *argv[]) { | |
std::string str = exec("brew list"); | |
std::ofstream output; | |
output.open("log.txt"); | |
if (output.is_open()) | |
output << str; | |
output.close(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#include
using namespace std;
int main()
{
int num1, num2, res;
cout<<"Enter Two Numbers: ";
cin>>num1>>num2;
res = num1+num2;
cout<<endl<<"Addition Result = "<<res<<endl;
res = num1-num2;
cout<<endl<<"Subtraction Result = "<<res<<endl;
res = num1*num2;
cout<<endl<<"Multiplication Result = "<<res<<endl;
res = num1/num2;
cout<<endl<<"Division Result = "<<res<<endl;
return 0;
}