C program to Copy the Contents of One file into another using fputc

C program to Copy the Contents of One file into another using fputc.



The C library function int fputc(int char, FILE *stream) writes a character specified by the argument char to the specified stream and advances the position indicator for the stream.

Following is the declaration for fputc( ) function.
  int fputc(int char, FILE *stream)

char - This is the character to be written. This is passed as its int promotion.

stream - This is the pointer to a FILE object that identifies the stream where the character is to be written.

If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.


--------------------------------------------------------------------------------------------------------------------------

#include<stdio.h>
#include<process.h>
void main( );
{
   FILE *fp1,*fp2;
   char a;
   clrscr( );
   fp1 = fopen("test.txt","r");
   if (fp1 == NULL)
   {
      puts("cannot open this file");
      exit(1);
    }
   fp2 = fopen("test1.txt","w");
   if (fp2 == NULL)
   {
      puts(" Not able to open this file");
      fclose(fp1);
      exit(1);
   }
do
{
  a = fgetc(fp1);

  fputc(a,fp2);
} while (a!=EOF);
fcloseall( );
getch( );
}

--------------------------------------------------------------------------------------------------------------------------

Explanation

--------------------------------------------------------------------------------------------------------------------------

We have two files, opening one file in read mode and another one on write mode.
    fp1 = fopen("test.txt","r");  and
  fp2 = fopen("test.txt","w");

Check whether file is opened successfully or not using NULL check.
  if(fp2 == NULL)
{
    // File is Not Opened Successfully
}

If everything is ok then reading file character by character and writing on file character by character.
      a = fgetc(fp1);

If we get EOF character then process of writing on the file will be terminated.
do
{
a = fgetc(fp1);
fputc(a,fp2);
} while(a! = EOF);

--------------------------------------------------------------------------------------------------------------------------

Output

--------------------------------------------------------------------------------------------------------------------------

Content will be written Successfully to file.



EmoticonEmoticon