Answer to Question 33C-1
// Usage: copy A B
// Create a copy of file A called B.
#include <cstdio>
using namespace std;
//========================================================
// copy
//========================================================
// copy(oldf,newf) copies all of file oldf into file newf.
//
// Requirement: oldf must have been opened for reading and
// newf must have been opened for writing.
//
// Note: This function does not close oldf or newf.
// It just does the copy.
//========================================================
void copy(FILE* oldf, FILE* newf)
{
int c = getc(oldf);
while(c != EOF)
{
putc(c, newf);
c = getc(oldf);
}
}
//========================================================
// openInfile
//========================================================
// Open 'fileName' for reading and return the open file.
// If 'fileName' cannot be opened, print a message and
// return NULL.
//========================================================
FILE* openInfile(const char* fileName)
{
FILE* inf = fopen(fileName, "r");
if(inf == NULL)
{
printf("Cannot open file %s for reading\n", fileName);
return NULL;
}
return inf;
}
//========================================================
// openOutfile
//========================================================
// Open 'fileName' for writing and return the open file.
// If 'fileName' cannot be opened, print a message and
// return NULL.
//========================================================
FILE* openOutfile(const char* fileName)
{
FILE* outf = fopen(fileName, "w");
if(outf == NULL)
{
printf("Cannot open file %s for writing\n", fileName);
return NULL;
}
return outf;
}
//========================================================
// main
//========================================================
int main(int argc, char* argv[])
{
if(argc == 3)
{
//---------------
// Open inf.
//---------------
FILE* inf = openInfile(argv[1]);
if(inf == NULL)
{
return 1;
}
//---------------
// Open outf.
//---------------
FILE* outf = openOutfile(argv[2]);
if(outf == NULL)
{
fclose(inf);
return 1;
}
//---------------
// Do the copy.
//---------------
copy(inf, outf);
fclose(inf);
fclose(outf);
return 0;
}
else // wrong number of command-line arguments
{
printf("usage: copy old new\n");
return 1;
}
}