c++ Read Entire File Contents Into Standard String

There are those occasions when an entire text file needs to be read in its entirety.

[codesyntax lang=”cpp”]

void fBufFrame::fileToString(string inFile, string & obuf)
    streampos size;
    char * memblock;
      The binary file stream does the majority of our groudwork
    std::ifstream file (inFile, ios::in|ios::binary|ios::ate);
    if (file.is_open())
        // On successful read of the file the process continues here
        size = file.tellg(); // determine the file size
        memblock = new char [size]; // allocate a memory block that can contain the file entirely
        file.seekg (0, ios::beg);  // initilize the IO process
        file.read (memblock, size);// fill the memory block with the contents of the file
        file.close(); // close the binary stream
        obuf = memblock; // initilize the standard string
        delete[] memblock; // Free resourced allocate to the memory block
    // if the initial read fails set the obuf variabel to a nil string
    else obuf = "";



Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

Leave a Reply

Your email address will not be published. Required fields are marked *