Bra*_*rad 21 c++ buffer fstream stl 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;`
Run Code Online (Sandbox Code Playgroud)
有没有人知道如何在不使用inbetween缓冲区的情况下将整个文件写入字符串流?
Ben*_*ley 27
// 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));
Run Code Online (Sandbox Code Playgroud)
pin*_*x33 27
ifstream f(fName);
stringstream s;
if (f) {
s << f.rdbuf();
f.close();
}
Run Code Online (Sandbox Code Playgroud)
在文档中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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37856 次 |
| 最近记录: |