使用 fstream 显式保存文件而不关闭 C++ 中的文件

Explicitly saving the file using fstream without closing the file in C++

WRT 代码,我想 显式 "save" 文件而不调用 close()。我知道没有必要调用 close() 因为 fsteam 将调用析构函数并在 fstream 对象超出范围时保存文件。

But i want to "explictly" save the file without waiting for fstream object to go out of scope. Is there a way to do this in C++ ? Is there anything like

flHtmlFile.save()

我知道的唯一选择是关闭它并再次打开它?

#include <fstream>

int main()
{
    std::ofstream flHtmlFile;
    std::string fname = "some.txt";
    flHtmlFile.open(fname);
    flHtmlFile << "text1"; // gets written
    flHtmlFile.close(); // My purpose is to EXPLICITLY SAVE THE FILE. Is there anything like flHtmlFile.save()
    flHtmlFile << "text2"; // doesn't get written 'coz i called close()
    return 1;
}

如果你只想让你写的内容尽快到达文件系统,那么在文件上调用flush

flHtmlFile.flush();

不需要关闭或重新打开。

文件通常是一些字节流,并且可能比您的虚拟地址大得多 space(例如,您可以在一台只有几千兆字节 RAM 的机器上拥有一个 TB 大小的文件)。

一般情况下,程序不会将文件的所有内容都保存在内存中。

一些库使您能够一次读取或写入内存中的所有内容(如果它适合的话!)。例如。 Qt has a QFile class with an inherited readAll成员函数。

但是,文件流(来自 C 标准库的 FILE,或来自 C++ 标准库的 std::ostream)被缓冲。您可能想要刷新缓冲区。在 Linux 上使用 std::flush (in C++) or fflush (in C); they practically often issue some system calls (probably write(2)) 要求操作系统将一些数据写入某个文件(但他们可能不保证数据已到达磁盘)。

确切地发生的是文件系统、操作系统和硬件特定的。在 Linux、page cache may keep the data before it is written to disk (so if the computer loses power, data might be lost). And disk controller hardware also have RAM and are somehow buffering. See also sync(2) and fsync(2) (and even posix_fadvise(2)...)。因此,即使您刷新了一些流,您也不确定这些字节是否已永久写入磁盘(您通常不关心)。

(在您的 C++ 代码和真实硬件之间有 很多层 很多缓冲

顺便说一句,您可以通过 std::ostringstream in C++ (or open_memstream in C on POSIX), flush that stream, then do something with its memory data (e.g. write(2) 将其写入磁盘)。