C Program to Copy Text From One File to Other File
Program : Copy Text From One File to Other File
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 | #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { FILE *fp1, *fp2; char ch; clrscr(); fp1 = fopen("Sample.txt", "r"); fp2 = fopen("Output.txt", "w"); while (1) { ch = fgetc(fp1); if (ch == EOF) break; else putc(ch, fp2); } printf("File copied Successfully!"); fclose(fp1); fclose(fp2); } |
Explanation :
To copy a text from one file to another we have to follow following Steps :
Step 1 : Open Source File in Read Mode
1 | fp1 = fopen("Sample.txt", "r"); |
Step 2 : Open Target File in Write Mode
1 | fp2 = fopen("Output.txt", "w"); |
Step 3 : Read Source File Character by Character
1 2 3 4 5 6 7 8 | while (1) { ch = fgetc(fp1); if (ch == EOF) break; else putc(ch, fp2); } |
- “fgetc” will read character from source file.
- Check whether character is “End Character of File” or not , if yes then Terminate Loop
- “putc” will write Single Character on File Pointed by “fp2” pointer
Input Text File :
Output Written on File