Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read from memory just like from a file using iostream?

I have simple text file loaded into memory. I want to read from memory just like I would read from a disc like here:

ifstream file;
string line;

file.open("C:\\file.txt");
if(file.is_open())
{
    while(file.good())
    {
        getline(file,line);         
    }
}   
file.close();

But I have file in memory. I have an address in memory and a size of this file.

What I must do to have the same fluency as with dealing with file in the code above?

like image 807
Mariusz Pawelski Avatar asked Dec 03 '10 14:12

Mariusz Pawelski


1 Answers

You can do something like the following..

std::istringstream str;
str.rdbuf()->pubsetbuf(<buffer>,<size of buffer>);

And then use it in your getline calls...

NOTE: getline does not understand dos/unix difference, so the \r is included in the text, which is why I chomp it!

  char buffer[] = "Hello World!\r\nThis is next line\r\nThe last line";  
  istringstream str;
  str.rdbuf()->pubsetbuf(buffer, sizeof(buffer));
  string line;
  while(getline(str, line))
  {
    // chomp the \r as getline understands \n
    if (*line.rbegin() == '\r') line.erase(line.end() - 1);
    cout << "line:[" << line << "]" << endl;
  }
like image 87
Nim Avatar answered Sep 21 '22 15:09

Nim