码迷,mamicode.com
首页 > 编程语言 > 详细

Running shell commands by C++

时间:2017-10-26 15:37:45      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:for   com   while   nice   class   pop   ref   ons   pen   

    #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++

标签:for   com   while   nice   class   pop   ref   ons   pen   

原文地址:http://www.cnblogs.com/hhbeast/p/7736435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!