Files - 5 Example on Files

/* Program to copy the contents of one file into another file. This resembles the DOS copy command */

#include< stdlib.h >


#include< stdio.h >


main()
{


FILE *fp1, *fp2;
int count=0;
char c, fname1[30],fname2[30];

printf( "\n Enter the Source file name ");
gets(fname1);
x:
fp1=fopen( fname1, "r" );
if(fp1 == NULL)
  {
   printf ( "\n Error in opening the source file \n \n Enter the source file name once again ");
   gets(fname1);
   count++;
   if( count == 3)
     exit(1);
   goto x;
  }
printf("\n Enter the Destination file name ");
gets(fname2);

fp2=fopen( fname2, "w" );
  while( 1 )
    {
     c = getc( fp1 );
     if(c==EOF) break;
     putc(c,fp2);
    }
fclose(fp1);
fclose(fp2);

}

       In the above program initially required variables are declared. A file name is accepted and opened using fopen() function. If it returns NULL a proper error message is displayed and asked to enter the correct file name also a variable count is incremented by 1 and this process is repeated for until count becomes 3 and then same repeats the program will exit. If the file name is entered correctly and if it exists its reference will assigned to pointer to FILE fp1 then the destination file will be accepted and its reference is assigned to pointer to FILE fp2. In while loop, first a character from source file will be read and stored into variable c. If it is EOF(End Of File) it stops the execution of while loop and continues the statement written after the while loop. Otherwise (i.e. if it is not EOF) the character present in character variable will be written into destination file. This process repeats until EOF occours. After executing the program check the contents of destination file in any of the text editor.

Comments