如何确保在C++中一次将整个字符串写入文件

huangapple go评论62阅读模式
英文:

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

问题

我想执行一个“进程间通信”,使用文件作为中间媒介。生产者向文件写入消息,消费者读取它。

我的问题是关于生产者。

假设这段代码:

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

int main() {
  // 创建并打开一个“中间文件”IPC
  ofstream messagefile("filename.txt");

  // 向文件写入内容
  messagefile << "文件可能有些棘手,希望您一次性读取所有这些字符串\n";

  // 关闭文件
  messagefile.close();
}

是否存在缓冲区刷新的风险(在任何OS或std lib的级别)将此字符串分成多个部分?我想确保消费者进程一次性读取整个消息。你有什么建议?

我知道消费者可以等待特定字符,比如“\n”,但我的问题是关于生产者。

英文:

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 &lt;iostream&gt;
#include &lt;fstream&gt;
using namespace std;

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

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

  // 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.

答案1

得分: 3

如果您担心由于系统崩溃可能导致信息丢失,我建议您使用ostream::flush以及某种依赖于操作系统的调用,将I/O缓冲区真正刷新到磁盘(比如在Unix系统上的sync())。

如果您只关心IPC协议(即,您只想避免读取部分消息),使用终止符应该足够了。在某些情况下,使用两个不同的分隔符“标记”(开始和结束)可能会有用。

我假设您一次只有一个活跃的写入者。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月18日 01:38:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定