How can I read from memory just like from a file using iostream?(如何从内存中读取,就像使用 iostream 从文件中读取一样?)
问题描述
我将简单的文本文件加载到内存中.我想从内存中读取,就像从这里读取光盘一样:
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 从文件中读取一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从内存中读取,就像使用 iostream 从文件中读取一样?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01