Programming Wiki: Reading a file into a string

Programming Wiki : CppFileIO

WikiHomePage :: Categories :: PageIndex :: RecentChanges :: RecentlyCommented :: Login/Register
I ofthen have problems with file I/O in g++ on different OS's and compilers.

Techniques for:

Reading a file into a string

istream iterator
ifstream InFile( "detlog.txt" );
if( !InFile ) {
cerr << "Couldnt open input file" << endl;

// 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;

while 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");
buf += line;
std::cout << "read: " << buf << "\n";
return 0;

Creating object for in, peeking at next char and reading in char:
//open file
ifstream schIn( schLstFileName.c_str(), ios::in );
if(!schIn) {   
    cerr<< endl<< ">>Can not open search file: "<< schLstFileName<< endl;
} else {
    schLstIsOpenable = true;
    while( schIn.peek() != EOF )
        //read in char by char
        while( schIn.peek() == ' ' || schIn.peek() == '\t' ) (char*)ch, sizeof(char) );

        if( ch[0] == 'a' || ch[0] == 'A' )

Creating object for in, reading line, and storing in a string:
    char line[220];
    string temp_name;

    ifstream ndxIn( outFileName.c_str(), ios::in | ios::binary );
    while( ndxIn.peek() != EOF )
        //line will be < 100  char long. other methods of getline cause problems
        ndxIn.getline( (char*)line, 100 );
        //getline( ndxIn, temp_name, '\n' );    //this works.......
        //for some reason takes much much LONGER
        temp_name = line;

Appending new output to a file:
    ofstream fout( string_holding_filename.c_str(), ios::out | ios::binary | ios::app );
    fout<< foo_string<< endl;

Output. Appending to a file using .write():
    //write it to end of file
    ofstream authorOut( name_of_file.c_str(), ios::out | ios::binary | ios::app );
    //write the offset to the lst_authorFN
    authorOut.write( (char*)foo_string.c_str(), sizeof(char)*foo_string.length() );

Above example, using a string stream. The goal here was to store a integer in a file in a fixed space of 8 characters.
Probably an easier way. Maybe using output formatting controls from iostream. include sstream
    //write offset to lst_author file
    ostringstream stringStream;            //stream integer into a string
    stringStream<< foo_integer;

    //holds 8 bytes of spaces   This loop fills up beginning area with spaces.
    for( int x=0; x < (8-stringStream.str().length()); x++ )
        authorOut.write( (char*)" ", sizeof(char) );

    //Write the integer (now held in the string stream) to the file.
    authorOut.write( (char*)stringStream.str().c_str(), sizeof(char)*stringStream.str().length() );

It may be useful to have a file stream object created in a class and used in several of the classes functions. When reopening a new file using the same objects sometimes funny things happen. Ex. On solaris it doesn't automatically reset the fail bit. Using .clear() solves these problems:
    bool fileOpenSuccess = true;

    fin.clear();    //object flags have to be reset..
            //if not fin is FALSE and even though open is success
            //fin remains false and states that file is not open.
            //WHY? Does .open function no reset the fail bit????????
            // fileName.c_str(), ios::in | ios::binary );

    if(!fin) {
        cerr<< "--Can not open file: "<< fileName<< endl;
        fileOpenSuccess = false;

There are no comments on this page. [Add comment]

Powered by Wikka Wakka Wiki
Page was generated in 0.0533 seconds