"Nobody You Know" <ap*******@hushmail.com> wrote in message
news:24**************************@posting.google.c om...
My goal is to efficiently read a file into a c++ string, discarding
newlines. Here is my first cut:
bool MyClass::ReadFile( string strFileName )
{
ifstream File( strFileName.c_str() );
if ( !File )
{
return false;
}
else
{
m_strFileData.reserve( 10000 );
char Char;
while ( File.get( Char ) )
{
if ( Char != '\n' )
m_strFileData += Char;
}
File.clear();
File.close();
return true;
}
}
I'm sure there's a better (i.e., faster) way. Can anyone help out?
Thanks!
Instead of reading character by character I'd propose to use istream
iterators.
ifstream InFile( "detlog.txt" );
if( !InFile ) {
cerr << "Couldn´t open input file" << endl;
return false;
}
// create reader objects
istream_iterator<string> DataBegin( InFile );
istream_iterator<string> DataEnd;
Now you can iterate using these istream_iterators and append their values to
a string for example:
while( DataBegin != DataEnd ) {
m_strFileData += *DataBegin;
DataBegin++;
}
HTH
Chris