In C file handling, we can transfer data from one file to another file using file operations. In this program, one file is opened in read mode and another file is opened in write mode. The fgetc() function reads characters from the source file, and the fputc() function writes those characters into the destination file.
How It Works?
fopen() in "rt" mode for reading.fopen() in "wt" mode for writing.fgetc().fputc().fclose().#include <stdio.h> #include <conio.h> main() { FILE *fp, *fp2; char ch; clrscr(); fp = fopen("file2.c", "rt"); fp2 = fopen("filenew.c", "wt"); if(fp == NULL || fp2 == NULL) { printf("Error opening file(s)"); return; } while((ch = fgetc(fp)) != EOF) { fputc(ch, fp2); printf("%c", ch); } fclose(fp); fclose(fp2); getch(); }
Content of file2.c is copied into filenew.c:
fgetc() and fputc() functions.source.txt in read mode ("rt") and copy.txt in write mode ("wt"). Read each character from the source file and write it into the destination file.
#include <stdio.h> #include <conio.h> main() { FILE *fp, *fp2; char ch; clrscr(); fp = fopen("source.txt", "rt"); fp2 = fopen("copy.txt", "wt"); while((ch = fgetc(fp)) != EOF) { fputc(ch, fp2); printf("%c", ch); } fclose(fp); fclose(fp2); getch(); }
Data copied successfully.
fgetc() function reads characters from the source file, and fputc() writes them into the destination file.