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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With