我正在编写一个C ++应用程序,我需要读取系统命令的结果。
我在用 popen()
或多或少如此处所示:
const int MAX_BUFFER = 2048;
string cmd="ls -l";
char buffer[MAX_BUFFER];
FILE *stream = popen(cmd.c_str(), "r");
if (stream){
while (!feof(stream))
{
if (fgets(buffer, MAX_BUFFER, stream) != NULL)
{
//here is all my code
}
}
pclose(stream);
}
我一直试图以不同的方式重写这个。我看到一些非标准的解决方案,如:
FILE *myfile;
std::fstream fileStream(myfile);
std::string mystring;
while(std::getline(myfile,mystring))
{
// .... Here I do what I need
}
我的编译器不接受这个。
我该怎么读? popen
在C ++中?
你的例子:
FILE *myfile;
std::fstream fileStream(myfile);
std::string mystring;
while(std::getline(myfile,mystring))
不起作用,因为虽然你非常接近,但标准库并没有提供 fstream
可以用a构建 FILE*
。 提升iostreams 但是提供了一个 iostream
可以从文件描述符构造,你可以从一个 FILE*
通过电话 fileno
。
例如。:
typedef boost::iostreams::stream<boost::iostreams::file_descriptor_sink>
boost_stream;
FILE *myfile;
// make sure to popen and it succeeds
boost_stream stream(fileno(myfile));
stream.set_auto_close(false); // https://svn.boost.org/trac/boost/ticket/3517
std::string mystring;
while(std::getline(stream,mystring))
别忘了 pclose
后来还是。
注意:较新版本的boost已弃用构造函数,只需要一个 fd
。相反,你需要通过其中一个 boost::iostreams::never_close_handle
要么 boost::iostreams::close_handle
作为构造函数的强制性第二个参数。
这是我写回来的东西,可以帮助你。它可能有一些错误。
#include <vector>
#include <string>
#include <stdio.h>
#include <iostream>
bool my_popen (const std::string& cmd,std::vector<std::string>& out ) {
bool ret_boolValue = true;
FILE* fp;
const int SIZEBUF = 1234;
char buf [SIZEBUF];
out = std::vector<std::string> ();
if ((fp = popen(cmd.c_str (), "r")) == NULL) {
return false;
}
std::string cur_string = "";
while (fgets(buf, sizeof (buf), fp)) {
cur_string += buf;
}
out.push_back (cur_string.substr (0, cur_string.size () - 1));
pclose(fp);
return true;
}
int main ( int argc, char **argv) {
std::vector<std::string> output;
my_popen("ls -l > /dev/null ", output);
for ( std::vector<std::string>::iterator itr = output.begin();
itr != output.end();
++itr) {
std::cout << *itr << std::endl;
}
}