Thursday, December 3, 2009

review quiz 3


#include < stdio.h >

int main (int argc, char* argv[], char* e[]){
int i;
printf("%d\n", argc);

printf("PRINT ARGUMENTS\n");
for(i=0; i < argc; i++) {
printf("%d : %s\n", i, argv[i]);
}

printf("\nPRINT ENVIRONMENT\n\n");
for(i=0; e[i]; i++) {
printf("%d : %s\n", i, e[i]);
}
return 0;
}

Tuesday, December 1, 2009

write copy file template


=========================================
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;
}