C Program to copy contents from file to another file
Program
#define _GNU_SOURCE
#include<stdio.h>
#include<stdlib.h>
int copy_file(FILE *srcFp, FILE *destFp);
void main()
{
FILE *srcFp, *destFp;
int status;
char src_file_name[30], dest_file_name[30];
printf("Enter the source file name:\n");
scanf(" %s", src_file_name);
srcFp = fopen(src_file_name, "r");
printf("Enter the destination file name:\n");
scanf("%s", dest_file_name);
destFp = fopen(dest_file_name, "w");
status = copy_file(srcFp, destFp);
if(status == 1)
printf("File %s copied to %s successfully\n", src_file_name, dest_file_name);
else
printf("Unable to copy.");
}
int copy_file(FILE *srcFp, FILE *destFp)
{
int ch;
if(srcFp == NULL)
{
puts("Error!!! Cannot open file.\n");
return -1;
}
if(destFp == NULL)
{
puts("Error!!! Cannot open file.\n");
fclose(srcFp);
return -1;
}
while((ch = fgetc(srcFp)) != EOF)
{
fputc(ch, destFp);
}
fcloseall();
return 1;
}
Output
Enter the source file name:
source.txt
Enter the destination file name:
dest.txt
File source.txt copied to dest.txt successfully