Answer to Question stdio-inf-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);
  }
}

//========================================================
//                    main
//========================================================

int main(int argc, char* argv[])
{
  if(argc == 3)
  {
    //---------------
    // Open inf.
    //---------------

    FILE* inf = fopen(argv[1], "r");
    if(inf == NULL)
    {
      printf("Cannot open file %s for reading\n", argv[1]);
      return 1;
    }

    //---------------
    // Open outf.
    //---------------

    FILE* outf = fopen(argv[2], "w");
    if(outf == NULL)
    {
      fclose(inf);
      printf("Cannot open file %s for writing\n", argv[2]);
      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;
  }
}