How to write a C Program to copy a file to another file in C Programming Language ?
This C Program to copy a file to another file.
Solution:
- #include<stdio.h>
- void main()
- {
- FILE *fp1,*fp2;
- char ch;
- char fname1[30],fname2[30];
- printf("Enter the source file: ");
- fflush(stdin);
- scanf("%s",fname1);
- printf("Enter the destination file: ");
- fflush(stdin);
- scanf("%s",fname2);
- fp1=fopen(fname1,"r");
- fp2=fopen(fname2,"w");
- if(fp1==NULL)
- {
- printf("\n cannot open file %s for reading",fname1);
- exit(1);
- }
- else if(fp2==NULL)
- {
- printf("\n cannot open file %s for writing",fname2);
- exit(1);
- }
- else
- {
- ch=getc(fp1);
- while(ch!=EOF)
- {
- putc(ch,fp2);
- ch=getc(fp1);
- }
- fclose(fp1);
- fclose(fp2);
- printf("\n files copied");
- }
- }