Running shell commands by C++
阿新 • • 發佈:2017-10-26
mman buffer space lose feo ret while != close
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; string cmdinput; string GetStdoutFromCommand(string cmd) { string data; FILE * stream; const int max_buffer = 256; char buffer[max_buffer]; cmd.append(" 2>&1"); stream = popen(cmd.c_str(), "r"); if (stream) { while (!feof(stream)) if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer); pclose(stream); } return data; } int main (){ cout << "Enter your command:" << endl; string cmdinput; getline (cin, cmdinput); cout << "Your command was ‘" << cmdinput << "‘" << endl; string com = GetStdoutFromCommand(cmdinput); cout << "Command: " << com << endl; return 0; }
in this way you can easy get the output string of your input command in C++
refer to http://www.cplusplus.com/forum/unices/144187/
Running shell commands by C++