私がストリームアウトするものの先頭と末尾に文字列を追加するのに、boost::iostreamsoutput filterを使用しようとしています。boost iostreams:output_filterは一度だけ動作します
以下のコードは動作しますが、初めてです。 2回目は、出力がどこかで失われているように見えますが、書き込みメソッドは呼び出されないようです。私は最初にストリームに何かを送って失敗ビットをトリガーすると思ったが、ストリームは良さそうだ。
MacとLinuxで最新のboost release (1.48)とsvn trunkという同じ問題が発生し、coutとデバイスとしてファイルシンクが発生します。
誰もが実際にこの作品を見ましたか?それはバグですか?または私のコードで何か間違っているのですか?
#include <iostream>
#include <sstream>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/operations.hpp>
using std::cin;
using std::cout;
using std::endl;
using std::streamsize;
using std::string;
using std::stringstream;
class add_string_output_filter
: public boost::iostreams::multichar_output_filter
{
public:
template<typename Sink>
streamsize write(Sink& sink, const char* s, streamsize n)
{
string out_string = string(s);
// remove trailing '\0' to prevent line break
if (out_string[out_string.size()-1] == '\0')
out_string = out_string.substr(0, out_string.size()-1);
string pre_string("prepended string - ");
string app_string(" - appended string");
stringstream sstrm;
sstrm << pre_string << out_string << app_string << endl;
// TODO: char* to string, back to char* ?!?
return boost::iostreams::write(sink,
sstrm.str().c_str(),
sstrm.str().length());
}
};
int main()
{
boost::iostreams::filtering_ostream out;
out.push(add_string_output_filter());
out.push(cout);
// string #01 is printed,
// string #02 gets lost
out << "string #01" << endl;
out << "string #02" << endl;
}