Skip to content

July 17, 2014

C++ Example: A Class to Read a File

by noise

Here is a C++ example of a class to read content of a text file and store it in a buffer (char *). Everything is done in class’s constructor.

The header file (ReadFromFile.h):

#include <iostream>
#include <fstream>
using namespace std;
class ReadFromFile {
    string fileName;
    long long buffLength;
    char *buff;
    ReadFromFile(string file);
    char* displayBuffer();
    long long getFileLength();

The implementation file (ReadFromFile.cpp):

#include "ReadFromFile.h"
ReadFromFile::ReadFromFile(string file) {
    fileName = file;
    ifstream is;;
    if (
    is.seekg(0, is.end);
    buffLength = is.tellg();
    is.seekg (0, is.beg);
    buff = new char[buffLength+1];, buffLength);
ReadFromFile::~ReadFromFile() {
   delete[] buff;
char* ReadFromFile::displayBuffer() {
    return buff;
long long ReadFromFile::getFileLength() {
    return buffLength;

The main file (main.cpp):

#include <iostream>
#include "ReadFromFile.h"
using namespace std;
int main(int argc, const char * argv[]) {
    ReadFromFile *readFile = new ReadFromFile("test.txt");
    cout << readFile->displayBuffer() << endl;
    delete readFile;
    return 0;

For this example you will need to create a file called test.txt.

Read more from C and C++ Examples

Leave a Reply


Note: HTML is allowed. Your email address will never be published.

Subscribe to comments