Jas, try this solution and see if it fits your needs:
Code:
#include <iostream>
#include <fstream>
using namespace std;
/* Prototype for the callback function.
*
* 1st param - a data chunk
* 2nd param - size of the data chunk
*
* returns - new transformed data, the WalkFile function automatically deletes
* it with the delete[] operator, so make sure you allocate it with the new[]
* operator also the second parameter must be set to the size of this data
*/
typedef char* (*walk_func_t)(const char*, int&);
/* Reads chunks of a given size from the input file and lets the given callback
* function transform the data, then writes the result to the output file.
*
* aInFilename - input file name
* aOutFilename - output file name
* aChunkSize - size of a single data chunk to read from the input file
* aWalkFunc - callback function which will be called with a data chunk passed to it
*/
void WalkFile(const char* aInFilename, const char* aOutFilename, int aChunkSize, walk_func_t aWalkFunc)
{
ifstream fin(aInFilename);
ofstream fout(aOutFilename);
char* bufferIn = new char[aChunkSize];
while (fin.good())
{
fin.read(bufferIn, aChunkSize);
int bufSize = fin.gcount();
char* bufferOut = (*aWalkFunc)(bufferIn, bufSize);
if (bufferOut != NULL && bufSize > 0)
fout.write(bufferOut, bufSize);
delete[] bufferOut;
}
delete[] bufferIn;
fout.close();
fin.close();
}
// Sample transform function (turns data uppercase)
char* Encode(const char* aData, int& aSize)
{
// If the size of the output buffer is different than the size of the input
// buffer, the aSize variable has to be modified!
char* dataOut = new char[aSize];
for (int i = 0; i < aSize; ++i)
dataOut[i] = toupper(aData[i]);
return dataOut;
}
// Sample transform function (turns data lowercase)
char* Unencode(const char* aData, int& aSize)
{
// If the size of the output buffer is different than the size of the input
// buffer, the aSize variable has to be modified!
char* dataOut = new char[aSize];
for (int i = 0; i < aSize; ++i)
dataOut[i] = tolower(aData[i]);
return dataOut;
}
int main(int argc, char* args[])
{
WalkFile("test.txt", "enc.txt", 350, &Encode);
WalkFile("enc.txt", "unenc.txt", 350, &Unencode);
cout << "Press ENTER to quit . . .";
cin.ignore();
return 0;
}
Basically, you have to call the WalkFile function and pass the names of the in/output files, size of the data to read at a time and the callback function. The latter will receive a chunk of data and will have to return a new one with the modified contents. See comments for more info.
The problem you may encounter is that you may want to call a non-static member function of your class, if that's the case then the code has to be modified, ask if you need further details.
Bookmarks