Boost_iostreams usage issue (Not writing to the file)

36 views Asked by At

Usecase: I am trying to write a logging function which writes to a .gz (compressed) file or a non-compressed file based on user input.

My code:

typedef boost::iostreams::filtering_streambuf<boost::iostreams::output> boost_output_buffer;
.
.
.

fstream *tmp_file;
if(_compressed){
    tmp_file = new ofstream(file_path, ios_base::out | ios_base::binary | ios_base::app);
} else {
    tmp_file = new ofstream(file_path, ios_base::out | ios_base::app);
}
boost_output_buffer *outbuf = new boost_output_buffer();
if(_compressed){
    outbuf->push(*(new boost::iostreams::gzip_compressor()));
}
outbuf->push((*tmp_file));
_fileStreamPtr = new ostream(outbuf);
.
.
.
(*_fileStreamPtr) << "Hello World\n";

Note that I am using pointers everywhere because I have already tried without them, and honestly I wasn't sure where I was going wrong so I tried using pointers. (In my use case I want these pointers and opened files till the end of my code, so deallocation doesn't matter)

For _compressed = false, this code creates a file at "file_path", but doesn't output any text to it.

Please help.

EDIT
As mentioned in the comments, I tried producing a minimum example.
Even on using this, the "Hello World" gets printed only once the program exits. How can I ensure this get printed at "<<" line itself?
(I am not sure but I think closing the file has a significant overhead. If that is true, then I don't want that since I am doing this operation a large number of times in my project)

#include <fstream>
#include <iostream>
#include <string>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include "unistd.h"

using namespace std;
typedef boost::iostreams::filtering_streambuf<boost::iostreams::output> boost_output_buffer;

int main(int argc, char* argv[]){

    ofstream tmp_file(argv[1], ios_base::out | ios_base::app);

    boost_output_buffer outbuf;
    outbuf.push(tmp_file);

    ostream mystream(&outbuf);

    (mystream) << "Hello World\n";

    sleep(15);

    return 0;
}
0

There are 0 answers