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 th
In the documentation for ostream
, there are several overloads for operator<<. One of them takes a streambuf*
and reads all of the streambuffer's contents.
Here is a sample use (compiled and tested):
#include
#include
#include
#include
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);
}