C Program to Copy Text From One File to Other File
The file I/O functions and types in the C language are easy to understand. To make use of these functions and types you have to include stdio library.
The C library function int fgetc(FILE *stream) gets the next character from the specified stream and advances the position indicator for the stream.
⦁ The declaration for fgetc( ) function is int fgetc(FILE *stream)
⦁ Stream is the pointer to a FILE object that identifies the stream on which the operation is to be performed.
⦁ This function returns the character read as an unsigned char cast to an int or EOF or error
--------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main( )
{
FILE *fp1,*fp2;
char ch;
clrscr();
fp1 = fopen("Example.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);
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
To copy a text from one file to another we have to follow following steps.
⦁ Open Source File in Read Mode
fp1 = fopen("Example.txt","r");
⦁ Open Target File in Write Mode
fp2 = fopen("Output.txt","w");
⦁ Read Source File Character by Character
while(1){
ch = fgetc(fp1);
if(ch==EOF)
break;
else
putc(ch,fp2);
}
Input Text File
C Programming Language
Output Written on File
C Programming Language
EmoticonEmoticon