=========================================
TEMPLATE CLASS
=========================================
template
class CopyFormattedFile {
ifstream *fin;
ofstream *fout;
public:
CopyFormattedFile(const char *fromFileName, const char *toFileName); // constructor
~CopyFormattedFile(); // destructor
int copy(); // copy file, return 0 when success
};
template
CopyFormattedFile::CopyFormattedFile(const char *fromFileName, const char *toFileName)
{
fin = new ifstream(fromFileName, ios::in|ios::binary);
fout = new ofstream(toFileName, ios::out|ios::binary);
}
template
CopyFormattedFile::~CopyFormattedFile()
{
delete fin;
delete fout;
}
template
int CopyFormattedFile::copy()
{
Type rec;
if(!fin->is_open() || !fout->is_open()) {
return -1;
}
while(!fin->fail() && !fout->fail()) {
fin->read((char *)&rec, sizeof(Type));
if(fin->gcout() == sizeof(Type)) { // gcount() function return the last read bytes
fout->write((char *)&rec, sizeof(Type));
}
else {
return -1; // file format error
}
}
return fin->feof() ? 0 : -1; // return 0 only when having copied all content
}
================================
TEMPLATE FUNCTION:
================================
template
int copy(const char *fromFileName, const char *toFileName)
{
ifstream *fin = new ifstream(fromFileName, ios::in|ios::binary);
ofstream *fout = new ofstream(toFileName, ios::out|ios::binary);
Type rec;
if(!fin->is_open() || !fout->is_open()) {
return -1;
}
while(!fin->fail() && !fout->fail()) {
fin->read((char *)&rec, sizeof(Type));
if(fin->gcout() == sizeof(Type)) { // gcount() function return the last read bytes
fout->write((char *)&rec, sizeof(Type));
}
else {
return -1; // file format error
}
}
int ret = fin->feof() ? 0 : -1; // return 0 only when having copied all content
delete fin;
delete fout;
return ret;
}
Tuesday, December 1, 2009
write copy file template
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment