c++ostream

How to be sure of writing the whole string to file at once in C++


I want to do an "inter-process communication" with a file in the middle. producer writes messages to the file and the consumer reads it.

my question is about the producer.

assume this code:

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

int main() {
  // Create and open a "file in the middle" IPC
  ofstream messagefile("filename.txt");

  // Write to the file
  messagefile << "Files can be tricky, hope you are reading all of this string at once\n";

  // Close the file
  MyFile.close();
} 

Is there any risk that buffer flush (at any level of OS or std lib) flushes this string in more than one part? I want to ensure that consumer processes read the whole message in one shot. What do you suggest?

I know the consumer can wait for a specific character like "\n", but my question is about the producer.


Solution

  • If you're concerned about the possible loss of information because of a system crash, I would suggest you to use ostream::flush plus some kind of operating system dependent call for really flushing the I/O buffers to disk (like sync() on Unix systems).

    If you're just concerned about the IPC protocol (that is, you just want to avoid reading partial messages), the use of a terminator should be enough. Two different separate "marks" (beginning and end) may be useful in some situations.

    I assume you just have one writer active at a time.