读取popen会产生C++

Ste*_*ano 11 c++ fstream file stream popen

我正在编写一个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);
    }
Run Code Online (Sandbox Code Playgroud)

我一直试图以不同的方式重写这个.我看到一些非标准的解决方案,如:

FILE *myfile;
std::fstream fileStream(myfile);
std::string mystring;
while(std::getline(myfile,mystring))
{
    // .... Here I do what I need
}
Run Code Online (Sandbox Code Playgroud)

我的编译器不接受这个.

如何从popenC++中读取?

Fle*_*exo 16

你的例子:

FILE *myfile;
std::fstream fileStream(myfile);
std::string mystring;
while(std::getline(myfile,mystring))
Run Code Online (Sandbox Code Playgroud)

不起作用,因为虽然你非常接近,但标准库并没有提供fstream可以用a构建的FILE*.然而,Boost 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))
Run Code Online (Sandbox Code Playgroud)

别忘了pclose以后.

注意:较新版本的boost已弃用构造函数,只需要一个fd.相反,您需要将一个boost::iostreams::never_close_handleboost::iostreams::close_handle作为强制性的第二个参数传递给构造函数.

  • 没编译,我想接收器应该是源,因为它是一个只读的例子.提高::输入输出流:: file_descriptor_source (2认同)