无论如何我可以将数据从 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;`
有没有人知道如何在不使用inbetween缓冲区的情况下将整个文件写入字符串流?
4 回答
在
ostream
的文档中,有several overloads for operator<< . 其中一个需要streambuf*
并读取所有streambuffer的内容 .这是一个示例用法(编译和测试):
使用C标准库的唯一方法是使用
ostrstream
而不是stringstream
.您可以使用自己的char缓冲区构造一个
ostrstream
对象,然后它将获得缓冲区的所有权(因此不再需要复制) .但请注意,
strstream
标头已被弃用(尽管它仍然是C 03的一部分,并且很可能在大多数标准库实现中始终可用),如果您忘记空终止数据,您将遇到大麻烦提供给ostrstream . 这也适用于流操作符,例如:ostrstreamobject << some_data << std::ends;
(std::ends
null终止数据) .