2

Is there a way to implicitly flush data to an output stream?

#include <iostream>
#include <fstream>
using namespace std;

#define log logstream 

int main()
{
  ofstream logstream("test.log");

  log << "Test1" << 123 << endl;     // explicitly flushed
  log << "Test2" << 123;             // ?

  // Test2 not written, yet...

  cout << "Check log file..." << endl;
  int tmp;
  cin >> tmp;
}

I would like to be able to log without specifying the << endl manipulator every time.

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 2
    Use `<< flush` instead? – Ed Heal Sep 22 '16 at 17:33
  • 1
    It's pretty standard across most languages that output streams are flushed on a `newline` or stream close. C++ is no different. Many logging classes implement a timer under the covers, and force a flush when the timer expires. – CAB Sep 22 '16 at 17:40
  • 3
    @EdHeal: that is *explicit* not *implicit*. – Jarod42 Sep 22 '16 at 17:41

1 Answers1

3

You may use std::unitbuf.

log << std::unitbuf;

And then flush would be done at each insertion.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • So for the log stream I have to specify `log << std::unitbuf;` once, and then everything will be flushed straight away? And the other streams will be unaffected? – Pietro Sep 22 '16 at 17:53
  • 1
    _"flush would be done at each insertion"_ That sounds incredibly inefficient :/ – πάντα ῥεῖ Sep 22 '16 at 17:53
  • @πάνταῥεῖ - Yes, but it can be good for logging, when you typically do not buffer. – Pietro Sep 22 '16 at 17:55
  • @Pietro: That only applies to the stream `log`. – Jarod42 Sep 22 '16 at 18:04
  • @Jarod42: It applies to any output stream, e.g.: `std::cout << std::unitbuf;` – Pietro Sep 23 '16 at 06:14
  • 1
    @Pietro: I mean that `log << std::unitbuf;` doesn't modify `std::cout` behavior, ,and indeed, you may also use `std::cout << std::unitbuf;` to affect `std::cout`. – Jarod42 Sep 23 '16 at 07:23