How do I read the results of a system() call in C++?

后端 未结 9 936
醉梦人生
醉梦人生 2020-12-17 06:44

I\'m using the following code to try to read the results of a df command in Linux using popen.

#include  // file an         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 07:28

    Thanks to everyone who took the time to answer. A co-worker pointed me to the ostringstream class. Here's some example code that does essentially what I was attempting to do in the original question.

    #include  // cout
    #include  // ostringstream
    
    int main(int argc, char** argv) {
        FILE* stream = popen( "df", "r" );
        std::ostringstream output;
    
        while( !feof( stream ) && !ferror( stream ))
        {
            char buf[128];
            int bytesRead = fread( buf, 1, 128, stream );
            output.write( buf, bytesRead );
        }
        std::string result = output.str();
        std::cout << "" << std::endl << result << "" << std::endl;
        return (0);
    }
    

提交回复
热议问题