如何用C++打印system()输出

How to print system() output in C++?

本文关键字:输出 system 打印 何用 C++      更新时间:2023-10-16
String cmd = "/alcatel/omc3/osm/script/proc_upd.pl -s stop -p MFSUSMCTRL -u" + userName;      
system(cmd); 

我想打印system()函数的输出。我该怎么做?

您可以使用函数popen。它将允许您获得命令的结果。必须将#include <stdio.h>添加到代码中才能使用它。基本语法为FILE * file_name = popen("command", "r")。您的代码可能看起来像:

#include <iostream>
#include <stdio.h>
using namespace std;
char buf[1000];
string userName;
int main() {
    cout << "What is your username?nUsername:";
    //input userName
    cin >> userName;
    //declare string strCMD to be a command with the addition of userName
    string strCMD = "/alcatel/omc3/osm/script/proc_upd.pl -s stop -p MFSUSMCTRL -u" + userName;
    //convert strCMD to const char * cmd
    const char * cmd = strCMD.c_str();
    //execute the command cmd and store the output in a file named output
    FILE * output = popen(cmd, "r");
    while (fgets (buf, 1000, output)) {
        fprintf (stdout, "%s", buf);
    }
    pclose(output);
    return 0;
}