Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to copy the content of file into another file.

C Code Example — File Handling Programs

ADVERTISEMENT

C Program to copy the content of file into another file.

Objective

Write a C program to copy the contents of one file into another file.

Algorithm / Approach

  1. Open the source file (fp1) in Read ("r") mode.
  2. Open the destination file (fp2) in Write ("w") mode.
  3. Check if the source file opened successfully.
  4. Use a while loop with ch = fgetc(fp1) until EOF.
  5. Inside the loop, write the character to the second file: fputc(ch, fp2).
  6. Close both files.
main.c
#include<stdio.h>
int main( ) {
 FILE *fp1, *fp2;
   fp1 = fopen("data.txt", "r");
   fp2 = fopen("data_cpy.txt", "w");


 if (fptr1 != NULL)  {
  ch = fgetc(fp1);
  while (ch != EOF)
    {
      fputc(ch, fp2);
      ch = fgetc(fp1);
    }
    printf("File Copied.");
   }
 printf("Files merged successfully.");
 fclose(fp1);
 fclose(fp2);
 return 0;
}

Expected Output

File Copied.

Explanation of the Program

  • Copying a file is just a combination of the Read program and the Write program.
  • We create two file pointers simultaneously. We read one byte from the first pointer, immediately push that byte into the second pointer, and repeat until the first file runs out of data.

Complexity

Time Complexity O(n) - Where n is the file size in bytes.
Space Complexity O(1)

Common Mistakes

  • Variable naming mismatches. The provided code declares fp1, but later checks if (fptr1 != NULL). It also uses ch without declaring it as a char variable first. These will cause compilation errors.
ADVERTISEMENT