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