如何使用POSIX在C ++中执行命令并获取命令的输出? [英] How to execute a command and get output of command within C++ using POSIX?
问题描述
我正在寻找一种方法来在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;
}
取代 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: 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. Pre-C++11 version: Replace 这篇关于如何使用POSIX在C ++中执行命令并获取命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! popen
和与
和
>
std::string result = system( "./some_command" ) ;
#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;
}
#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;
}
popen
and pclose
with _popen
and _pclose
for Windows.