如何像使用wistream从文件中读取内存一样? [英] How can I read from memory just like from a file using wistream?

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

问题描述

在我的>上一个中问题,我问如何从内存中读取文件和从文件中读取数据.因为我的整个文件都在内存中,所以我想以类似的方式读取它.

In my previous question I asked how to read from a memory just as from a file. Because my whole file was in memory I wanted to read it similarly.

我发现

I found answer to my question but actually I need to read lines as a wstring. With file I can do this:

wifstream file;
wstring line2;

file.open("C:\\Users\\Mariusz\\Desktop\\zasoby.txt");
if(file.is_open())
{
    while(file.good())
    {
        getline(file,line2);
        wcout << line2 << endl;
    }
}   
file.close();

即使文件是ASCII格式.

Even if the file is in ASCII.

现在,我只是使用

Right now I'm simply changing my string line to wstring with a function from this answer. However, I think if there is a way to treat this chunk of memory just like a wistream it would be a faster solution to get this lines as wstrings. And I need this to be fast.

所以有人知道如何将这部分内存视为wistream吗?

So anybody know how to treat this chunk of memory as a wistream?

推荐答案

我假设您的数据已转换为所需的编码(请参见@detunized答案).

I assume that your data is already converted into the desired encoding (see @detunized answer).

使用如果您

If you insist on not using boost then the conversion goes as follows (still straight forward):

class membuf : public wstreambuf // <- !!!HERE!!!
{
    public:
        membuf(wchar_t* p, size_t n) { // <- !!!HERE!!!
        setg(p, p, p + n);
    }
};

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

    wistream istr(&mb);
    wstring line;
    while(getline(istr, line))
    {
        wcout << L"line:[" << line << L"]" << endl;
    }
}

还要考虑,以了解为什么使用普通 UTF-8流.

Also consider this for why use plain char UTF-8 streams.

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

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