Saturday, 17 January 2015

File Structures - C Program to copy characters from one file to another file.


This is a C Program which copies the contents from one file to another file.

Here we use file pointer to read and write data. To read data we open a file in read mode and similarly to write data we open a file in write mode . Read and write modes are shown by 'r' and 'w' , these should be passed as an second argument for fopen function.

PROGRAM :
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp1,*fp2;

    fp1 = fopen("input.txt" ,"r");
    fp2 = fopen("output.txt","w");

    while(1)
    {
        char ch;
        ch = fgetc(fp1);
        if (ch == EOF)
            break;
        else
            putc(ch, fp2);
    }
    fclose(fp1);
    fclose(fp2);

    return 0;
}


OUTPUT :

First create a file named input.txt in the root directory of the project,

Create a new file input.txt

Now open that file and write some data in it,

Write some data in input.txt file

Now run the c file which we created above, then it will create a new file output.txt
The file output.txt is automatically created after executing our program

Now open that output.txt file , we will see the data from input.txt copied to output.txt file.

Contents copied from input.txt to output.txt

No comments:

Post a Comment