You are on page 1of 2

EX.

NO : 4 COPY THE CONTENTS OF ONE FILE TO ANOTHER


DATE :

AIM:
To write a C program to copy the contents of one file to another.

ALGORITHM:
1. Start the program.
2. Create the source file, destination file and set their path.
3. Open the source file in r (read) and destination file in w (write) mode.
4. Read character from source file and write it to destination file using fputc ().
5. Repeat step 3 till source file has reached end.
6. Print the result.
7. Stop the program.

PROGRAM:
/* Copy the contents of one file to another */
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE *fptr1, *fptr2;
char filename [100], c;
printf (“Enter the filename to open for reading: ”);
scanf (“% s”, filename);
fptr1 = fopen (filename, “r”);
if (fptr1 == NULL)
{
printf (“Cannot open file %s”, filename);
exit (0);
}
printf (“Enter the filename to open for writing: ”);
scanf (“% s”, filename);
fptr2 = fopen (filename, “w”);
if (fptr2 == NULL)
{
printf (“Cannot open file %s”, filename);
exit (0);
}
c = fgetc (fptr1);
while (c != EOF)
{
fputc (c, fptr2);
c = fgetc (fptr1);
}
printf (“Contents copied to %s”, filename);
fclose (fptr1);

1
fclose (fptr2);
getch ();
return 0;
}

OUTPUT:
Enter the filename to open for reading: myread.txt
Enter the filename to open for writing: mywrite.txt
Contents copied to mywrite.txt

RESULT:
Thus, the implementation to copy the contents of one file to another was
implemented successfully.

You might also like