将数据从fstream复制到stringstream,没有缓冲区? [英] Copy data from fstream to stringstream with no buffer?
本文介绍了将数据从fstream复制到stringstream,没有缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
还有,我可以从 fstream
(一个文件)传输数据到 stringstream
内存)?
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;`
推荐答案
// need to include <algorithm> and <iterator>, and of course <fstream> and <sstream>
ifstream fin("input.txt");
ostringstream sout;
copy(istreambuf_iterator<char>(fin),
istreambuf_iterator<char>(),
ostreambuf_iterator<char>(sout));
这篇关于将数据从fstream复制到stringstream,没有缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文