codescracker


c

C Program to Copy File



« Previous Program Next Program »


Copy File in C

To copy the content of one file to the other file in C programming, you have to first open the source file then open target file and start reading the source file's content character by character and place or write the content of the source file to target file character by character at the time of reading

C Programming Code to Copy File

Following C program ask to the user to enter the two file name. First file name is source file (the content of this file is going to copy to the target file) and the second name is target file (the content of the source file is copied to this target file). After entering the two file name, the below program start copying the content of the source file to the target file. After copying it will print/display a message saying File copied Successfully..!! :

/* C Program - Copy File */
		
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	FILE *fs, *ft;
	char ch, fname1[20], fname2[20];
	printf("Enter source file name with extension (like files.txt) : ");
	gets(fname1);
	fs=fopen(fname1, "r");
	if(fs==NULL)
	{
		printf("Error in opening source file..!!");
		getch();
		exit(1);
	}
	printf("Enter target file name with extension (like filet.txt) : ");
	gets(fname2);
	ft=fopen(fname2, "w");
	if(ft==NULL)
	{
		printf("Error in opening target file..!!");
		fclose(fs);
		getch();
		exit(2);
	}
	while(1)
	{
		ch=fgetc(fs);
		if(ch==EOF)
		{
			break;
		}
		else
		{
			fputc(ch, ft);
		}
	}
	printf("File copied successfully..!!");
	fclose(fs);
	fclose(ft);
	getch();
}

When the above c program is compile and executed, it will produce the following result:

c program to copy file

After running the above c program, your target file will contain the source file's content

Same Program in Other Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test