开发者

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?


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;
  }


You can use istringstream for that.

string text = "text...";
istringstream file(text);
string line;

while(file.good())
{
    getline(file,line);         
}


Use boost.Iostreams. Specifically basic_array.

namespace io = boost::iostreams;

io::filtering_istream in;
in.push(array_source(array, arraySize));
// use in


I found a solution that works on VC++ since Nim solution works only on GCC compiler (big thanks, though. Thanks to your answer I found other answers which helped me!).

It seems that other people have similar problem too. I did exactly as here and here.

So to read from a piece of memory just like form a istream you have to do this:

class membuf : public streambuf
{
    public:
        membuf(char* p, size_t n) {
        setg(p, p, p + n);
    }
};

int main()
{
    char buffer[] = "Hello World!\nThis is next line\nThe last line";  
    membuf mb(buffer, sizeof(buffer));

    istream istr(&mb);
    string line;
    while(getline(istr, line))
    {
        cout << "line:[" << line << "]" << endl;
    }
}

EDIT: And if you have '\r\n' new lines do as Nim wrote:

if (*line.rbegin() == '\r') line.erase(line.end() - 1);

I'm trying to treat this memory as as wistream. Does anybody know how to do this? I asked separate question for this.


Use

std::stringstream

It has an interface to manipulate and read strings just like other streams.


Here's how I would do it:

#include <sstream>

std::istringstream stream("some textual value");
std::string line;
while (std::getline(stream, line)) {
    // do something with line
}

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜