刷新流

默认情况下,文件流是缓冲的,许多其他类型的流也是如此。这意味着对流的写入可能不会导致基础文件立即更改。在 oder 中强制所有缓冲写入立即发生,你可以刷新流。你可以通过调用 flush() 方法或通过 std::flush 流操作器直接执行此操作:

std::ofstream os("foo.txt");
os << "Hello World!" << std::flush;

char data[3] = "Foo";
os.write(data, 3);
os.flush();

有一个流操作器 std::endl 结合写一个换行符和刷新流:

// Both following lines do the same thing
os << "Hello World!\n" << std::flush;
os << "Hello world!" << std::endl;

缓冲可以提高写入流的性能。因此,进行大量编写的应用程序应避免不必要的刷新。相反,如果不经常进行 I / O,应用程序应考虑频繁刷新,以避免数据卡在流对象中。