Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string>
  4.  
  5. std::string exec(const char* cmd, const std::string &input) {
  6.     FILE *input_pipe = popen(cmd, "w");
  7.     FILE *output_pipe = popen(cmd, "r");
  8.  
  9.     if (!output_pipe || !input_pipe) {
  10.         throw std::ios_base::failure("invalid command");
  11.     }
  12.  
  13.     fputs(input.c_str(), input_pipe);
  14.     pclose(input_pipe);
  15.  
  16.     char buffer[128];
  17.     std::string result = "";
  18.     while (!feof(output_pipe)) {
  19.         if (fgets(buffer, 128, output_pipe) != NULL) {
  20.             result += buffer;
  21.         }
  22.     }
  23.  
  24.     pclose(output_pipe);
  25.     return result;
  26. }
  27.  
  28. int main() {
  29.     const char *cmd = "./other";
  30.     std::cout << "output is \n" << exec(cmd, "3\n2 4 5");
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement