Advertisement
AntonioVillanueva

PIPE & cmd linux

Nov 16th, 2018
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdexcept>
  3. #include <stdio.h>
  4. #include <string>
  5. /********************************************************************************/ 
  6. using namespace std;
  7. /********************************************************************************/ 
  8. std::string exec(const char* cmd) {
  9.     char buffer[128];
  10.     std::string result = "";
  11.     FILE* pipe = popen(cmd, "r");
  12.     if (!pipe) throw std::runtime_error("popen() failed!");
  13.     try {
  14.         while (!feof(pipe)) {
  15.             if (fgets(buffer, 128, pipe) != NULL)
  16.                 result += buffer;
  17.         }
  18.     } catch (...) {
  19.         pclose(pipe);
  20.         throw;
  21.     }
  22.     pclose(pipe);
  23.     return result;
  24. }
  25. /********************************************************************************/ 
  26. int main(){
  27.     std::cout <<  exec( "ls");
  28. }
  29. /********************************************************************************/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement