#include<stdio.h> void main() { /* File_1.txt is the file with content and, File_2.txt is the file in which content of File_1 will be copied. */ FILE *fp1, *fp2; char ch; int pos; if ((fp1 = fopen("File_1.txt","r")) == NULL) { printf("\nFile cannot be opened"); return; } else { printf("\nFile opened for copy...\n "); } fp2 = fopen("File_2.txt", "w"); fseek(fp1, 0L, SEEK_END); // file pointer at end of file pos = ftell(fp1); fseek(fp1, 0L, SEEK_SET); // file pointer set at start while (pos--) { ch = fgetc(fp1); // copying file character by character fputc(ch, fp2); } fcloseall(); }
Explanation:
1. In this step trying open the file File_1.txt in read mode
if ((fp1 = fopen("File_1.txt","r")) == NULL) { printf("\nFile cannot be opened"); return; }
2. Open the file File_2.txt in Write mode
fp2 = fopen("File_2.txt", "w");
3. Read Charecters from File_1.txt ( ch= fgetc(fp1); ) and at the same time it Write into File_2.txt ( fputc(ch, fp2); )
while (pos--) { ch = fgetc(fp1); // copying file character by character fputc(ch, fp2); }