如何使用 wistream 从内存中读取数据,就像从文件中读取数据一样?
在我的上一篇 我问的问题是如何像从文件中一样从内存中读取数据。因为我的整个文件都在内存中,所以我想以类似的方式读取它。
我发现 回答我的问题,但实际上我需要将行读取为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 格式的。
现在,我只需使用 这个答案。但是,我认为如果有一种方法可以像 wistream
一样处理这块内存,那么将这些行视为 wstring
会是一个更快的解决方案。我需要这个速度很快。
那么有人知道如何将这块内存视为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();
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 wstring
s. And I need this to be fast.
So anybody know how to treat this chunk of memory as a wistream
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您的数据已经转换为所需的编码(请参阅@detunized 答案)。
使用 我的回答你之前的问题转换是直接的:
如果你坚持不使用 boost 然后转换如下(仍然简单):
另请考虑 this 了解为什么使用纯
char
UTF-8 流。I assume that your data is already converted into the desired encoding (see @detunized answer).
Using my answer to your previous question the conversion is straight forward:
If you insist on not using boost then the conversion goes as follows (still straight forward):
Also consider this for why use plain
char
UTF-8 streams.您不能将 ASCII 字符串视为 UNICODE 字符串,因为它们包含的字符具有不同的大小。因此,您必须对临时缓冲区进行某种转换,然后使用该内存作为流的输入缓冲区。这就是你现在正在做的事情。
You cannot treat ASCII string as a UNICODE string, since the characters they contain have different sizes. So you would have to do some kind of conversion to a temporary buffer and then use that piece of memory as an input buffer for your stream. This is what you're doing right now.
很明显,如果您有
string
、istream
和istringstream
,那么您也有wstring
、<代码>wistream和wistringstream
。istringstream
和wistringstream
都只是分别针对 char 和 wchar 的模板类basic_istringstream
的特化。It should be obvious that if you have
string
,istream
, andistringstream
, therefore you also havewstring
,wistream
, andwistringstream
.Both
istringstream
andwistringstream
are just specialization of the template classbasic_istringstream
for char and wchar respectively.