Transfer The File One Place to Another


Explanation

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?

  • Step 1: Declare two file pointers for source and destination files.
  • Step 2: Open the first file using fopen() in "rt" mode for reading.
  • Step 3: Open the second file using fopen() in "wt" mode for writing.
  • Step 4: Read each character from the first file using fgetc().
  • Step 5: Write the character into the second file using fputc().
  • Step 6: Continue the process until the end of the file is reached.
  • Step 7: Close both files using fclose().

Example Program


#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();

}

Output

Content of file2.c is copied into filenew.c:

#include <stdio.h>

main()
{
  printf("Hello India");
}

Practice Exercises

Task 1: Write a C program to transfer the data from a file named source.txt to another file named copy.txt.

Goal: Learn how to copy data from one file to another using fgetc() and fputc() functions.

💡 Hint: Open 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.
💡 Show Solution

#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();

}

Output

Data copied successfully.

source.txt

Welcome To C Programming

copy.txt

Welcome To C Programming
Explanation: The program opens two files. The first file is opened in read mode to get data, and the second file is opened in write mode to store copied data. The fgetc() function reads characters from the source file, and fputc() writes them into the destination file.