Skip to content

Instantly share code, notes, and snippets.

@meritozh
Created April 5, 2016 07:12
Show Gist options
  • Save meritozh/f0351894a2a4aa92871746bf45879157 to your computer and use it in GitHub Desktop.
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.
#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;
}
@Anilp00
Copy link

Anilp00 commented Feb 11, 2024

#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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment