Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 is included in the text, which is why I chomp it!

  char buffer[] = "Hello World!
This is next line
The last line";  
  istringstream str;
  str.rdbuf()->pubsetbuf(buffer, sizeof(buffer));
  string line;
  while(getline(str, line))
  {
    // chomp the 
 as getline understands 

    if (*line.rbegin() == '
') line.erase(line.end() - 1);
    cout << "line:[" << line << "]" << endl;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...