I call to mind that always writing same codes related file managements with C++,
should prepare general file management class.
You could use it from the main file.
(This same codes are uploaded to GitHub).
(main.cc)
#include "loader.h" #include <sstream> #include <iostream> using namespace std; File* gFiles[ 10 ]; void createFile(int num, const char* filename) { Loader::instance()->createFile( &gFiles[num], filename); cout << num << " th file is created." << endl; } void outputFile(int num) { Loader::instance()->outputFile(gFiles[num]); } void loadFiles() { Loader::instance()->loadFiles(); cout << "files are loaded." << endl; } void destroyFile(int num) { Loader::instance()->destroyFile( &gFiles[num] ); cout << num << " th file is destroyed." << endl; } int main() { if ( !Loader::instance() ) { Loader::create(); } createFile(0, "./test.txt"); loadFiles(); outputFile(0); destroyFile(0); }
File class manages each files.
(file.h)
#ifndef INCLUDED_FILE_H #define INCLUDED_FILE_H #include <string> using namespace std; class File { private: File( const char* filename ); ~File(); friend class Loader; string mFilename; char* mData; int mSize; public: bool isReady() const; int getSize() const; const char* getData() const; }; #endif
(file.cc)
#include "file.h" #include <fstream> #include <assert.h> using namespace std; File::File( const char* filename ) : mFilename( filename ), mData( 0 ), mSize( 0 ) { } File::~File() { if ( mData ) { delete[]( mData ); } mSize = 0; } bool File::isReady() const { return ( mData != 0 ); } int File::getSize() const { assert( mData && "loading is not finished." ); return mSize; } const char* File::getData() const { assert( mData && "loading is not finished." ); return mData; }
Loader class manages a group of files.
(loader.h)
#ifndef INCLUDED_LOADER_H #define INCLUDED_LOADDR_H #include <list> #include <string> #include "file.h" using namespace std; class Loader { private: Loader(); Loader( const Loader& ); ~Loader(); list< File* > mFiles; static Loader* mInstance; public: static Loader* instance(); static void create(); static void destroy(); void createFile( File**, const char* filename ); void loadFiles(); void outputFile( File *f ); void destroyFile( File** ); }; #endif
(loader.cc)
#include "loader.h" #include "assert.h" #include <fstream> #include <iostream> using namespace std; Loader* Loader::mInstance = 0; Loader::Loader() { } Loader::~Loader() { typedef list< File* >::iterator It; for ( It i = mFiles.begin(); i != mFiles.end(); ++i ) { delete( *i ); } } Loader* Loader::instance() { return mInstance; } void Loader::create() { assert( !mInstance && "already created." ); mInstance = new Loader(); } void Loader::destroy() { delete( mInstance ); }