如何从内存读取,就像使用iostream的文件? [英] How can I read from memory just like from a file using iostream?

查看:135
本文介绍了如何从内存读取,就像使用iostream的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的文本文件加载到内存。我想从内存读取,就像我从这样的光盘读取:

  ifstream文件; 
string line;

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

但我有内存中的文件。我有一个在内存中的地址和这个文件的大小。



我必须做的以具有与上述代码中处理文件相同的流畅度吗?

解决方案

我发现一个解决方案适用于VC ++,因为 Nim 解决方案只适用于GCC编译器(非常感谢,谢谢你的回答我发现帮助我的其他答案。)



似乎其他人也有类似的问题。我完全按照这里这里。 p>

因此,从一个内存中读取一个istream,你必须这样做:

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

int main()
{
char buffer [] =Hello World!\\\
这是下一行\\\
最后一行;
membuf mb(buffer,sizeof(buffer));

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

EDIT:你有'\r\\\
'新行如Nim所写:

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






我试图将此记忆视为 wistream 。有人知道如何这样做吗?我问单独的问题< a>为此。


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?

解决方案

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.

这篇关于如何从内存读取,就像使用iostream的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆