gpt4 book ai didi

c++ - 我怎样才能像使用 wistream 从文件中读取一样从内存中读取?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:00 26 4
gpt4 key购买 nike

在我的previous question 我问的是如何像从文件中一样从内存中读取。因为我的整个文件都在内存中,所以我想以类似的方式读取它。

我找到了 answer对于我的问题,但实际上我需要将行读取为 wstring。使用文件我可以这样做:

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 格式。

现在我只是将我的 string 行更改为 wstring 并使用来自 this 的函数回答。但是,我认为如果有一种方法可以像 wistream 一样处理这 block 内存,那么将这些行作为 wstring 会是一个更快的解决方案。而且我需要它很快。

所以有人知道如何将这 block 内存作为 wistream 处理吗?

最佳答案

我假设您的数据已经转换为所需的编码(请参阅@detunized 回答)。

使用 my answer to your previous question转换很简单:

namespace io = boost::iostreams;

io::filtering_wistream in;
in.push(warray_source(array, arraySize));

如果你insist on not using boost然后转换如下(仍然很简单):

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

同时考虑 this为什么要使用纯 char UTF-8 流。

关于c++ - 我怎样才能像使用 wistream 从文件中读取一样从内存中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4353894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com