08-14-05 07:49 AM
niraj.kumar.ait@gmail.com wrote:
> how to read a (whole) binary file in a c++ string .
>
> Is there any terminating character for binary file .EOF doesnt work in
> binary file .
>
> When I use EOF it just read ELF char.
>
Below is a standard C++ program that will read an entire file
into a std::string.
Reading a file a character at a time is quite compute intensive.
#include <iostream>
#include <fstream>
#include <exception>
#include <vector>
#include <string>
struct readexception
: std::exception
{
std::string m_what;
~readexception() throw()
{
}
readexception( const std::string & i_what )
: m_what( i_what )
{
}
virtual const char* what() const throw()
{
return m_what.c_str();
}
};
std::string readtostring( const char * filename )
{
std::ifstream file( filename, std::ios::binary );
if ( ! file.good() )
{
throw readexception(std::string("Open failed '")+filename+"'");
}
// get length of file:
file.seekg( 0, std::ios::end );
std::streampos length = file.tellg();
file.seekg( 0, std::ios::beg );
// create a vector with all the bytes.
// Unfortunately, std::string is not guarenteed to use contiguous
// storage so to be conforming to the standard we need to copy
// all the bytes from somthing else to a string. std::vector
// is guarenteed to have contiguous bytes so we use std::vector.
std::vector<char> l_buffer( length );
// read data as a block:
std::streamsize l_numread=file.readsome(&l_buffer.front(),length);
if ( l_numread != length )
{
throw readexception(std::string("read failed '")+filename+"'");
}
// finally return the string
return std::string( &l_buffer.front(), l_numread );
}
int main( int argc, char ** argv )
{
if ( argc != 2 )
{
std::cerr << "usage: " << argv[0] << " <filename>\n";
return 1;
}
try {
std::cout << readtostring( argv[1] );
}
catch ( const readexception & l_ex )
{
std::cerr << "readtostring failed " <<l_ex.what()<<std::endl;
return 1;
}
}
[ Post a follow-up to this message ]
|