我有一个简单的文本文件加载到内存中。我想从内存中读取,就像从下面这样的磁盘读取一样:
ifstream file;
string line;
file.open("C:\\file.txt");
if(file.is_open())
{
while(file.good())
{
getline(file,line);
}
}
file.close();但我的内存里有文件。我在内存中有一个地址和这个文件的大小。
我必须做什么才能像在上面的代码中处理文件一样流畅?
发布于 2010-12-04 21:27:57
我找到了一个在VC++上工作的解决方案,因为Nim解决方案只能在GCC编译器上工作(不过,还是要谢谢你。多亏了你的回答,我找到了对我有帮助的其他答案!)
似乎其他人也有类似的问题。我完全像here和here那样做了。
因此,要像形成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;
}
}EDIT:,如果您有'\r\n‘新的行,就按照Nim写的那样做:
if (*line.rbegin() == '\r') line.erase(line.end() - 1);我试着把这段记忆当做wistream。有人知道怎么做吗?我向单独的question询问了这个问题。
发布于 2010-12-03 22:07:49
您可以执行类似以下的操作。
std::istringstream str;
str.rdbuf()->pubsetbuf(<buffer>,<size of buffer>);然后在你的getline调用中使用它...
注意:getline不理解dos/unix的区别,所以文本中包含了\r,这就是我为什么要咬它的原因!
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;
}发布于 2010-12-03 22:04:22
为此,您可以使用istringstream。
string text = "text...";
istringstream file(text);
string line;
while(file.good())
{
getline(file,line);
}https://stackoverflow.com/questions/4346240
复制相似问题