将boost::filtering_streambuf与newline_filter一起使用时为空文件



我想用boost::iostreams::filtering_streambufnewline_filter将一段数据写入通过std::fopen打开的文件。

这是一个小的可复制的测试用例,我一直在尝试使用它。

它只是生成一个空文件。

#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <errno.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/filter/newline.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <iosfwd>
#include <string>
#include <boost/iostreams/flush.hpp>
#include <boost/iostreams/operations.hpp>
#include <fstream>
#include <cstdio>
int main()
{
FILE *fp = nullptr;  
std::string d ("file");
fp = std::fopen(d.c_str(), "w");
const int fd = fileno(fp);
boost::iostreams::file_descriptor_sink output(fd, boost::iostreams::never_close_handle);
boost::iostreams::filtering_streambuf<boost::iostreams::output>obuf;
#if defined(_WIN32)
obuf.push(boost::iostreams::newline_filter(boost::iostreams::newline::dos));
#else
obuf.push(boost::iostreams::newline_filter(boost::iostreams::newline::mac));
#endif
obuf.push(output);
std::ostream buffer(&obuf);
std::string myteststr = "Hello n Worldn";
buffer << myteststr;
buffer.flush();
boost::iostreams::flush(obuf);
return 0;
}

我这里有没有明显遗漏的东西?

我无法再现这种行为:

在Coliru上直播 cco

这是用于的编译和执行

g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp -lboost_{system,iostreams} && ./a.out
file output.txt
xxd output.txt

打印

output.txt: ASCII text, with CRLF line terminators
00000000: 4865 6c6c 6f20 0d0a 2057 6f72 6c64 0d0a  Hello .. World..

我确实建议添加明确的fd关闭,尽管这在技术上并不重要。

此外,2019年是否有理由使用FILE*?我假设您之所以包含它,是因为遗留代码只使用它。


上市:

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/filter/newline.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/flush.hpp>
#include <cstdio>
#include <iostream>
#include <string>
int main() {
FILE* fp = std::fopen("output.txt", "w");
const int fd = fileno(fp);
boost::iostreams::file_descriptor_sink output(fd, boost::iostreams::never_close_handle);
boost::iostreams::filtering_streambuf<boost::iostreams::output> obuf;
obuf.push(boost::iostreams::newline_filter(boost::iostreams::newline::dos));
obuf.push(output);
std::ostream buffer(&obuf);
std::string myteststr = "Hello n Worldn";
buffer << myteststr;
buffer.flush();
boost::iostreams::flush(obuf);
::close(fd);
}

最新更新