![](/img/trans.png)
[英]How can I read from memory just like from a file using wistream?
[英]How can I read from memory just like from a file using iostream?
我有简单的文本文件加载到内存中。 我想从内存中读取,就像我从像这里的光盘中读到的那样:
ifstream file;
string line;
file.open("C:\\file.txt");
if(file.is_open())
{
while(file.good())
{
getline(file,line);
}
}
file.close();
但我有记忆中的档案。 我在内存中有一个地址和这个文件的大小。
我必须做些什么才能获得与上述代码中处理文件相同的流畅度?
您可以执行以下操作..
std::istringstream str;
str.rdbuf()->pubsetbuf(<buffer>,<size of buffer>);
然后在你的getline
调用中使用它...
注意: getline
不理解dos / unix差异,所以\\ r \\ n包含在文本中,这就是我为什么选择它!
char buffer[] = "Hello World!\r\nThis is next line\r\nThe last line";
istringstream str;
str.rdbuf()->pubsetbuf(buffer, sizeof(buffer));
string line;
while(getline(str, line))
{
// chomp the \r as getline understands \n
if (*line.rbegin() == '\r') line.erase(line.end() - 1);
cout << "line:[" << line << "]" << endl;
}
你可以使用istringstream
。
string text = "text...";
istringstream file(text);
string line;
while(file.good())
{
getline(file,line);
}
使用boost.Iostreams。 特别是basic_array
。
namespace io = boost::iostreams;
io::filtering_istream in;
in.push(array_source(array, arraySize));
// use in
我发现了一个适用于VC ++的解决方案,因为Nim解决方案仅适用于GCC编译器(非常感谢。感谢您的回答,我找到了其他帮助我的答案!)。
所以要从一块内存中读取就像形成一个istream一样,你必须这样做:
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;
}
}
编辑:如果你有'\\ r \\ n'新行,就像Nim写道:
if (*line.rbegin() == '\r') line.erase(line.end() - 1);
我正试图将这种记忆视为一种wistream
。 有人知道怎么做这个吗? 我为此问了一个单独的问题 。
使用
std::stringstream
它有一个操作和读取字符串的接口,就像其他流一样。
我是这样做的:
#include <sstream>
std::istringstream stream("some textual value");
std::string line;
while (std::getline(stream, line)) {
// do something with line
}
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.