在没有缓冲区的情况下将数据从 fstream 复制到 stringstream?
无论如何,我可以将数据从 fstream
(文件)传输到 stringstream
(内存中的流)吗?
目前,我正在使用缓冲区,但这需要双倍的内存,因为您需要将数据复制到缓冲区,然后将缓冲区复制到字符串流,直到删除缓冲区为止,数据都会在内存中复制。
std::fstream fWrite(fName,std::ios::binary | std::ios::in | std::ios::out);
fWrite.seekg(0,std::ios::end); //Seek to the end
int fLen = fWrite.tellg(); //Get length of file
fWrite.seekg(0,std::ios::beg); //Seek back to beginning
char* fileBuffer = new char[fLen];
fWrite.read(fileBuffer,fLen);
Write(fileBuffer,fLen); //This writes the buffer to the stringstream
delete fileBuffer;`
有谁知道如何在不使用中间缓冲区的情况下将整个文件写入字符串流?
Is there anyway I can transfer data from an fstream
(a file) to a stringstream
(a stream in the memory)?
Currently, I'm using a buffer, but this requires double the memory, because you need to copy the data to a buffer, then copy the buffer to the stringstream, and until you delete the buffer, the data is duplicated in the memory.
std::fstream fWrite(fName,std::ios::binary | std::ios::in | std::ios::out);
fWrite.seekg(0,std::ios::end); //Seek to the end
int fLen = fWrite.tellg(); //Get length of file
fWrite.seekg(0,std::ios::beg); //Seek back to beginning
char* fileBuffer = new char[fLen];
fWrite.read(fileBuffer,fLen);
Write(fileBuffer,fLen); //This writes the buffer to the stringstream
delete fileBuffer;`
Does anyone know how I can write a whole file to a stringstream without using an inbetween buffer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在
ostream
的文档中,有 < 的几个重载代码>运算符<<。其中之一采用streambuf*
并读取流缓冲区的所有内容。这是一个示例使用(编译和测试):
In the documentation for
ostream
, there are several overloads foroperator<<
. One of them takes astreambuf*
and reads all of the streambuffer's contents.Here is a sample use (compiled and tested):
使用 C++ 标准库的唯一方法是使用
ostrstream
而不是stringstream
。您可以使用自己的 char 缓冲区构造一个 ostrstream 对象,然后它将获得该缓冲区的所有权(因此不需要更多复制)。
但请注意,
strstream
标头已被弃用(尽管它仍然是 C++03 的一部分,并且很可能在大多数标准库实现中始终可用),并且您将遇到大麻烦如果您忘记以空终止方式提供给 ostrstream 的数据。这也适用于流运算符,例如: ostrstreamobject <<一些_数据<< std::ends; (std::ends
null 终止数据)。The only way using the C++ standard library is to use a
ostrstream
instead ofstringstream
.You can construct a
ostrstream
object with your own char buffer, and it will take ownership of the buffer then (so no more copying is needed).Note however, that the
strstream
header is deprecated (though its still part of C++03, and most likely, it will always be available on most standard library implementations), and you will get into big troubles if you forget to null-terminate the data supplied to the ostrstream.This also applies to the stream operators, e.g:ostrstreamobject << some_data << std::ends;
(std::ends
nullterminates the data).如果您使用 Poco,这很简单:
If you're using Poco, this is simply: