本文介绍了在C ++中读取popen结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写C ++应用程序,我需要阅读系统命令的结果.

I am writing a C++ application and I need to read the result of a system command.

我正在或多或少地使用popen(),如下所示:

I am using popen() more or less as shown here:

    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);
    }

我一直试图用另一种方式来重写它.我看到了一些非标准的解决方案,例如:

I've been trying to re-write this in a different way. I saw some non-standard solutions like:

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

我的编译器虽然不接受.

My compiler does not accept this though.

如何从C ++中的popen中读取内容?

How can I read from popen in C++?

推荐答案

您的示例:

FILE *myfile;
std::fstream fileStream(myfile);
std::string mystring;
while(std::getline(myfile,mystring))

不起作用,因为尽管您与标准库非常接近,但标准库没有提供可以由FILE*构造的fstream. 增强iostream 确实提供了可以由文件描述符构造,您可以通过调用filenoFILE*中获得一个.

Does't work because although you're very close the standard library doesn't provide an fstream that can be constructed from a FILE*. Boost iostreams does however provide an iostream that can be constructed from a file descriptor and you can get one from a FILE* by calling 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_handleboost::iostreams::close_handle之一作为强制性第二个参数传递给构造函数.

Note: Newer versions of boost have deprecated the constructor which takes just a fd. Instead you need to pass one of boost::iostreams::never_close_handle or boost::iostreams::close_handle as a mandatory second argument to the constructor.

这篇关于在C ++中读取popen结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:40