C program to Copy the contents of one file into another using fputc
Program to copy the contents of one file into another using fgetc and fputc function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<stdio.h> #include<process.h> void main() { FILE *fp1, *fp2; char a; clrscr(); fp1 = fopen("test.txt", "r"); if (fp1 == NULL) { puts("cannot open this file"); exit(1); } fp2 = fopen("test1.txt", "w"); if (fp2 == NULL) { puts("Not able to open this file"); fclose(fp1); exit(1); } do { a = fgetc(fp1); fputc(a, fp2); } while (a != EOF); fcloseall(); getch(); } |
Output :
1 | Content will be written successfully to file |
Explanation of Program :
We have to files with us , we are opening one file in read mode and another file in write mode.
1 | fp1=fopen("test.txt","r"); |
and
1 | fp2=fopen("test1.txt","w"); |
It is better practice to check whether file is opened successfully or not using NULL check.
1 2 3 4 | if(fp2==NULL) { //File is Not opened Successfully } |
If everything goes right then we are reading file character by character and writing on file character by character.
1 | a = fgetc(fp1); //Reading Single Character |
End of File is specified by EOF character, thus if we get EOF character then process of writing on the file will be terminated.
1 2 3 4 | do { a = fgetc(fp1); fputc(a,fp2); }while(a!=EOF); |