This might be a rather unusual question but could anyone help please?
For some reason I need to save a file then reload it later on. The file is not very big (2-3Mb) but this has to be done so many times that it significantly slows down the computation. I was told that I could save the file in the memory instead. Does anyone know how to do this or at least where I should go to look for answers, please?
Here is how you write to memory like you would a file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <fstream> // writing to file
#include <sstream> // writing to memory (a string)
#include <string>
int main()
{
std::ofstream ofs("file.txt"); // open a file for writing
ofs << "Writing to file on disk"; // output to file
std::ostringstream oss; // open a string for writing EDIT: Fixed from original post
oss << "Writing to string in memory"; // output to string
return 0;
}
@suny
To read the whole file into the memory I recommend depending on what kind of operation you do on your file either 1. std::vector<std::string> : Storing each line in a separate string. This makes operations easy which only involves one line at a time.
2. std::vector<char> or std::string : To store the whole thing in one big string. If you are using binary files.
3. Some other data type specific to your file. Parse the file into this data structure once, then you can access is next time without re-parsing the whole thing