Reading a file into a string

N

Nobody You Know

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!
 
C

Chris Theis

Nobody You Know said:
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
 
F

Frank Schmitt

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!

Use getline:

#include <fstream>
#include <iostream>
#include <string>

// read contents of file "bla" into buf, discarding newlines
int main(int argc, char* argv[]) {
std::string buf;
std::string line;
std::ifstream in("bla");
while(std::getline(in,line))
buf += line;
std::cout << "read: " << buf << "\n";
return 0;
}

HTH & kind regards
frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top