I wish to write a piece of data to the file opened via std::fopen using boost::iostreams::filtering_streambuf with newline_filter.
Here is a small reproducible test case that I have been trying to work with.
It just produces an empty file.
#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 World\n";
buffer << myteststr;
buffer.flush();
boost::iostreams::flush(obuf);
return 0;
}
Is there something obvious that I am missing here ?
I can't reproduce that behaviour:
Live On Coliru¹
This for the compilation and execution with
Prints
I do suggest to add the explicit
fdclose, although that should not technically matter.Also, is there any reason to use
FILE*in 2019? I'm assuming you're including that because of legacy code that uses it only.¹ Listing: