How to save a file in memory

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?

Thanks a lot!
or if you are working with the bytes, you could just simple put them in a byte array.
hmm... maybe you can give us some (direct) example?
What data do you want to save?

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;
}
Last edited on
Galik wrote:
std::ostringstream oss("file.txt"); // open a string for writing

Are you sure it does what you think it does?
http://cplusplus.com/reference/iostream/ostringstream/ostringstream/

@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
R0mai wrote:
Are you sure it does what you think it does?


Whoops, yes, I did a classic cut'n'paste error.

I'll fix it.
Last edited on
For some reason I need to save a file then reload it later on.

What are you doing? Do you not know?

Do you mean caching the file in memory until it can be written to disk once later rather than writing it and reading it repeatedly during execution?
Topic archived. No new replies allowed.