如何使用POSIX在C ++中执行命令并获取命令的输出? [英] How to execute a command and get output of command within C++ using POSIX?

查看:399
本文介绍了如何使用POSIX在C ++中执行命令并获取命令的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来在C ++程序中运行时获取命令的输出。我已经看过使用system()函数,但只是执行一个命令。这里是我正在寻找的示例:

  std :: string result = system(./some_command); 

我需要运行一个任意命令并得到它的输出。我已经看过Boost.org,但我没有找到任何会给我需要的东西。

解决方案

  #include< cstdio> 
#include< iostream>
#include< memory>
#include< stdexcept>
#include< string>

std :: string exec(const char * cmd){
char buffer [128];
std :: string result =;
std :: shared_ptr< FILE> pipe(popen(cmd,r),pclose);
if(!pipe)throw std :: runtime_error(popen()failed!);
while(!feof(pipe.get())){
if(fgets(buffer,128,pipe.get())!= NULL)
result + = buffer;
}
return result;
}

Pre-C ++ 11版本:

  #include< iostream> 
#include< stdexcept>
#include< stdio.h>
#include< string>

std :: string exec(const char * cmd){
char buffer [128];
std :: string result =;
FILE * pipe = boen(cmd,r);
if(!pipe)throw std :: runtime_error(popen()failed!);
try {
while(!feof(pipe)){
if(fgets(buffer,128,pipe)!= NULL)
result + = buffer;
}
} catch(...){
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}

取代 popen >

I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will just execute a command. Here's an example of what I'm looking for:

std::string result = system( "./some_command" ) ;

I need to run an arbitrary command and get it's output. I've looked at Boost.org but I have not found anything that will give me what I need.

解决方案

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer, 128, pipe.get()) != NULL)
            result += buffer;
    }
    return result;
}

Pre-C++11 version:

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);
    return result;
}

Replace popen and pclose with _popen and _pclose for Windows.

这篇关于如何使用POSIX在C ++中执行命令并获取命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆