memory stream?

A

andrew

I am writing a program that involves reading in lots of (ASCII) data,
manipulating it, and then outputting some more. I am using ifstream and
ofstream.

Since I am reading a line, and writing a line at a time, my code can be
quite slow.

Is it possible, to use a memory stream, such that I read the entire
file in to memory first, and then can use it, just like a file stream?
Similarly, can I write to memory, just like I would be writing to a
file, and then write the entire data to disk?

Many thanks.
 
S

Stefan Chrobot

U¿ytkownik andrew napisa³:
> Is it possible, to use a memory stream, such that I read the entire
> file in to memory first, and then can use it, just like a file stream?
> Similarly, can I write to memory, just like I would be writing to a
> file, and then write the entire data to disk?
>
> Many thanks.
>

Yes, and it's easy. Just use stringstream. You can't construct
stringstream out of ifstream's buffer, but - as with all streams - you
can send the whole buffer to it.

#include <sstream>
#include <fstream>
using namespace std;

int main()
{
ifstream in("test.txt");
stringstream ss;
ss << in.rdbuf(); // Put the whole file into ss
// use ss as every other stream...
}

Stefan
 
M

maxim.yegorushkin

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,001
Messages
2,570,254
Members
46,849
Latest member
Fira

Latest Threads

Top