复制从fstream的数据,没有缓冲stringstream的?
-
27-09-2019 - |
题
反正我有可以从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;`
有谁知道我怎么能写整个文件到一个字符串流不使用插图中缓冲区?
解决方案
// 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));
其他提示
ifstream f(fName);
stringstream s;
if (f) {
s << f.rdbuf();
f.close();
}
在对于ostream
的文档中,有几个重载operator<<
。他们中的一个需要花费streambuf*
和读取所有的streambuffer的内容。
下面是一个样品使用(编译和测试):
#include <exception>
#include <iostream>
#include <fstream>
#include <sstream>
int main ( int, char ** )
try
{
// Will hold file contents.
std::stringstream contents;
// Open the file for the shortest time possible.
{ std::ifstream file("/path/to/file", std::ios::binary);
// Make sure we have something to read.
if ( !file.is_open() ) {
throw (std::exception("Could not open file."));
}
// Copy contents "as efficiently as possible".
contents << file.rdbuf();
}
// Do something "useful" with the file contents.
std::cout << contents.rdbuf();
}
catch ( const std::exception& error )
{
std::cerr << error.what() << std::endl;
return (EXIT_FAILURE);
}
使用C ++标准库的唯一方法是使用ostrstream
代替stringstream
的。
您可以构建一个ostrstream
对象与自己的字符缓冲区,这将需要缓冲区的所有权,然后(所以没有更多的复制需要)。
但是请注意,该strstream
头已被弃用(虽然C ++ 03,最有可能的还是它的一部分,它永远是适用于大部分标准库的实现),你将进入带来很大麻烦,如果你忘了空终止提供给ostrstream.This数据也适用于该流的运营商,例如:ostrstreamobject << some_data << std::ends;
(std::ends
nullterminates数据)
不隶属于 StackOverflow