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 {
private:
    string fileName;
    long long buffLength;
    char *buff;
 
public:
    ReadFromFile(string file);
    ~ReadFromFile();
 
    char* displayBuffer();
    long long getFileLength();
};

The implementation file (ReadFromFile.cpp):

#include "ReadFromFile.h"
 
ReadFromFile::ReadFromFile(string file) {
    fileName = file;
    ifstream is;
 
    is.open(file.c_str());
 
    if (is.fail())
          return;
 
    is.seekg(0, is.end);
    buffLength = is.tellg();
    is.seekg (0, is.beg);
 
    buff = new char[buffLength+1];
 
    is.read(buff, buffLength);
    is.close();
}
 
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

required
required

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

Subscribe to comments