Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost / outputting to a file

Can i output some text to a file using solely boost libraries?

The code i have (official documentation):

#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    io::stream_buffer<io::file_sink> buf("log.txt");
    std::ostream                     out(&buf);
    // out writes to log.txt
    out << "abc";
}

Is there another way? (i dont want to use std streams). Thanks in advance.

like image 271
Vis Viva Avatar asked Feb 03 '26 12:02

Vis Viva


2 Answers

Input and output in a C++ program can be done in four ways:

  1. Using C++ I/O streams. This is the recommended way. Even if using Boost I/O streams, it's all using the standard I/O streams behind the scene, and using the stream operators << and >>.
  2. The C FILE API: fopen, fprintf/fwrite/fgets/fread/etc. I think there are Boost I/O streams that handle FILE, but then you are still using the stream operators << and >>.
  3. On Windows, use of the POSIX subsystem file descriptors. I think these can also be used for Boost I/O streams.
  4. Native file handling. On POSIX systems (e.g. Linux, BSD, OSX) this is the same as 3 above, on Windows see e.g. this link.

Boost I/O streams isn't supposed to be a stand-alone API, instead it is using one of the above I/O systems to simplify some things for the programmer.

like image 188
Some programmer dude Avatar answered Feb 05 '26 01:02

Some programmer dude


io::stream_buffer is derived from std::basic_streambuf, so you can use native basic_streambuf public methods, or you can use boost::filesystem streams, but all of such classes are derived from std:: classes.

http://www.boost.org/doc/libs/1_50_0/libs/filesystem/doc/reference.html#File-streams

like image 39
ForEveR Avatar answered Feb 05 '26 00:02

ForEveR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!