我将简单的文本文件加载到内存中.我想从内存中读取,就像从这里读取光盘一样:
ifstream 文件;字符串线;file.open("C:\file.txt");如果(文件.is_open()){而(文件.好()){获取行(文件,行);}}file.close();
但我在内存中有文件.我在内存中有一个地址和这个文件的大小.
我必须做什么才能像上面代码中处理文件一样流畅?
我找到了一个适用于 VC++ 的解决方案,因为 Nim 解决方案仅适用于 GCC 编译器(不过非常感谢.感谢您的回答,我找到了其他答案帮助了我!).
其他人似乎也有类似的问题.我完全按照这里和此处.>
所以要像形成 istream 一样从一块内存中读取,你必须这样做:
class membuf : 公共流缓冲{上市:membuf(char* p, size_t n) {setg(p, p, p + n);}};int main(){char buffer[] = "Hello World!
这是下一行
最后一行";membuf mb(缓冲区,大小(缓冲区));istream istr(&mb);字符串线;while(getline(istr, line)){cout<<行:["<<线<<"]" <<结束;}}
如果你有 ' ' 新行,就像 Nim 写的那样:
if (*line.rbegin() == '
') line.erase(line.end() - 1);
<小时>
我试图将此内存视为 wistream
.有人知道怎么做这个吗?我问了单独的问题 为此.
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!
This is next line
The 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 ' ' new lines do as Nim wrote:
if (*line.rbegin() == '
') 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 从文件中读取一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!