Repository navigation
Files and Buffers
Warning
This page is still Work-in-Progress.
One of the most essential concepts in a data persistence library is data files. Files are how data propagates across sessions: when the program first runs, the wanted data is written to a file, which continues to exist even after the program closes. Then, when the program is then opened again, it may read from that file to restore its data.
As you might know, directly writing to a file on every write() will quickly prove to be inefficient, because writing data to a disk is far slower than, say, directly writing it to memory. So many persistence libraries, including cpersist use write buffers. A write buffer is a section in memory data is written to before it is written to the disk. Let us demonstrate.
#include <cpersist/cpersist.h>
int main() {
auto file = cpersist::File("myfile");
file.write("number", 3);
file.commit();
}First, we create a cpersist::File object. Because of the reasons we discussed earlier, this does not immediately create a file. Instead, it creates a buffer that will later be written into a file. We call it "myfile" and not, say, "mybuffer" because, although it is indeed a buffer, it's often easier to think of it as a file.
file.write("number", 3); writes the number 3 under the key "number." We will discuss write() functions in a later page.
file.commit(); is the important part. This line takes the file's buffer and dumps it into a file with the same name. After this function is called, a file with the name myfile.bin has been created and written the number 3 to. If you try opening the file, however, you will not see the number 3 directly. This is because of the way information is serialized. We will discuss serialization in a future chapter.