Copy File

C Programming

C Programming Examples

#include<stdio.h>
#include<stdlib.h>

int main() {

	/* Declare File pointer */
	FILE *source, *destination;
	char ch;

	/* Open file 'myfile.txt' in read mode */
	source = fopen("myfile.txt", "r");

	/* Checking for file is properly open or not */
	if(source == NULL) {
		printf("Error occur on file opening\n");
		exit(EXIT_FAILURE);
	}

	/* Create/Open file 'newfile.txt' in write mode */
	destination = fopen("newfile.txt", "w");

	/* Checking for file is properly open or not */
	if(destination == NULL) {
		fclose(source);
		printf("Error occur on file opening\n");
		exit(EXIT_FAILURE);
	}

	/* Copying text from one file to another */
	while( ( ch = fgetc(source) ) != EOF)
		fputc(ch, destination);

	/* Checking error on file */
	if (ferror(destination))
		printf("Error occur...Try Again!\n");
	else
		printf("File copied successfully!\n");								

	/* Close file */
	fclose(source);	
	fclose(destination);								
	return 0;
}


          /****** Output ******/
          

File copied successfully!

Learn more about File I/O in C