L-32 MCS 275 Fri 30 Mar 2001

Below are the programs we discussed in class.
/* L-32 MCS 275 Friday 30 March 2001 copying a file, basic version */

/* To run this program, there must be one file with name "my_input"
   in the current directory.  The program creates (or overwrites)
   the file with name "my_output" and copies the content of "my_input"
   into the file "my_output". */

#include <stdio.h>

int main()
{
   FILE *infile, *outfile;              /* pointers to input, output files */
   char c;

   infile = fopen("my_input","r");      /* open for reading */
   outfile = fopen("my_output","w");    /* open for writing */

   while (fscanf(infile,"%c",&c) == 1)  /* as long as one conversion */
      fprintf(outfile,"%c",c);          /* copy character to outfile */

   fclose(infile);                      /* close input file */
   fclose(outfile);                     /* close output file */

   return 0;
}
Here is a more graceful opening of the input file :
/* L-32 MCS 275 Friday 30 March 2001 copying a file, graceful version */

/* This program copies files.  The user is asked to provide the name
   of the input file.  Opening is done in a graceful manner :
   if the input file does not exist, then the user is asked to provide 
   another name. */

#include <stdio.h>

FILE *read_input_name ();
/* Asks the user for a file name and opens the file for input,
   if failure, then the user will be asked to retry. */

int main()
{
   FILE *infile, *outfile;              /* pointers to input, output files */
   char c;

   infile = read_input_name();          /* open for reading */
   outfile = fopen("my_output","w");    /* open for writing */

   while (fscanf(infile,"%c",&c) == 1)  /* as long as one conversion */
      fprintf(outfile,"%c",c);          /* copy character to outfile */

   fclose(infile);                      /* close input file */
   fclose(outfile);                     /* close output file */

   return 0;
}

FILE *read_input_name ()
{
   FILE *infile;
   char name[80];

   for (;;)
   {
      printf("Give name of the input file : ");
      scanf("%s", name);
      infile = fopen(name,"r");
      if (infile != NULL)
         break;
      else
         printf("File \"%s\" could not be opened.  Please try again...\n", name);
   }

   return infile;
}