Advertisement
AntonioVillanueva

Recupera texto en C++ al efectuar system

Jul 11th, 2022
1,369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. /*
  2.  * retrieve string response from a command , in linux
  3.  */
  4. #include <stdio.h>
  5.  
  6. #include <string>
  7. #include <iostream>
  8.  
  9. #include <sys/syscall.h>   /* Pour les définitions de SYS_xxx */
  10.  
  11. using namespace std;
  12.  
  13. string command="ps -aux | grep ttyUSB";
  14.  
  15. //retrieve string response from a command
  16. string GetStdoutFromCommand(string cmd) {
  17.  
  18.   string data;
  19.   FILE * stream;
  20.   const int max_buffer = 256;
  21.   char buffer[max_buffer];
  22.   cmd.append(" 2>&1");
  23.  
  24.   stream = popen(cmd.c_str(), "r");
  25.   if (stream) {
  26.     while (!feof(stream))
  27.       if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
  28.     pclose(stream);
  29.   }
  30.   return data;
  31. }
  32.  
  33. int main(int argc, char* argv[])
  34. {
  35. string tmp=GetStdoutFromCommand(command);
  36. cout <<tmp<<endl;
  37.    
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement