2012-03-19 26 views
1

我想使用管道與boost庫,我只是想執行一個後臺程序(例如:LS),並得到它的輸出在一個字符串(就像你可以做fopen和fread),但我真的不明白爲什麼我沒有輸出與此代碼:管道提升:: iostreams沒有任何輸出

#include <iostream> 
#include <cstdio> 
#include <sstream> 

#include <boost/iostreams/stream.hpp> 
#include <boost/iostreams/device/file_descriptor.hpp> 

int 
main(int argc, char** argv) 
{ 
    using namespace boost::iostreams; 

    if(argc < 2) { 
     return -1; 
    } 

    FILE* p = popen(argv[1], "r"); 

    if(! p) { 
     std::cerr << "error open pipe" << std::endl; 

     return -2; 
    } 

    int fd = fileno(p); 
    std::stringstream ss; 
    ss << fd; 
    std::string s = ss.str(); 

    file_descriptor_source pdesc(s); 
    stream_buffer<file_descriptor_source> pstream(pdesc); 

    std::istream is(&pstream); 
    std::string out; 

    while(is) { 
     std::getline(is, out); 
     std::cout << out << std::endl; 
    } 

    pstream.close(); 
    pdesc.close(); 
    pclose(p); 

    return 0; 
} 

在此先感謝。

+0

這可能與您的直接問題無關,但您的讀取循環錯誤地測試eof/failure。成語是先閱讀然後測試;你的代碼先測試然後讀取。所以,而不是'while(is){getline(is,out); ...}',你應該'while(getline(is,out)){...}'。 – Josh 2012-03-20 00:23:10

回答

2

看來你試圖從包含文件描述符編號的「路徑」打開一個boost::file_descriptor_source。但是,該名稱的文件可能不存在。你可能打算使用的是這樣的:

if (FILE* p = popen(argv[1], "r")) 
{ 
    boost::iostreams::file_descriptor_source d(fileno(p), boost::iostreams::close_handle); 
    boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> pstream(d); 
    std::cout << &pstream; 
    pclose(p); 
}