Reading popen results in C++

后端 未结 2 925
粉色の甜心
粉色の甜心 2020-12-06 06:32

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

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

    con         


        
相关标签:
2条回答
  • 2020-12-06 06:56

    Your example:

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

    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.

    E.g.:

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

    Don't forget to pclose later still.

    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.

    0 讨论(0)
  • 2020-12-06 06:59

    Here is something which i wrote long back, may help you. It might have some errors.

    #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;
            }
    
    }
    
    0 讨论(0)
提交回复
热议问题