Reputation: 3810
WRT code, i want to explicitly "save" the file without calling close(). i know there is no need to call close() as fsteam will call the destructor and save the file when fstream object goes out of scope.
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()
The only 1 option i know is to close it & open again ?
#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;
}
Upvotes: 2
Views: 6649
Reputation: 1
Files are often some stream of bytes, and could be much bigger than your virtual address space (e.g. you can have a terabyte sized file on a machine with only a few gigabytes of RAM).
In general a program won't keep all the content of a file in memory.
Some libraries enable you to read or write all the content at once in memory (if it fits there!). E.g. Qt has a QFile class with an inherited readAll member function.
However, file streams (either FILE
from C standard library, or std::ostream
from C++ standard library) are buffered. You may want to flush the buffer. Use std::flush (in C++) or fflush (in C); they practically often issue some system calls (probably write(2) on Linux) to ask the operating system to write some data in some file (but they probably don't guarantee that the data has reached the disk).
What exactly happens is file system-, operating system-, and hardware- specific. On Linux, the 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)...). So even if you flush some stream, you are not sure that the bytes are permanently written on the disk (and you usually don't care).
(there are many layers and lots of buffering between your C++ code and the real hardware)
BTW you might write into memory thru 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) it to disk).
Upvotes: 4
Reputation: 170064
If all you want is for the content you wrote to reach the file system as soon as possible, then call flush
on the file:
flHtmlFile.flush();
No closing or re-opening required.
Upvotes: 5