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
- Open the source file (
fp1) in Read ("r") mode. - Open the destination file (
fp2) in Write ("w") mode. - Check if the source file opened successfully.
- Use a
whileloop withch = fgetc(fp1)untilEOF. - Inside the loop, write the character to the second file:
fputc(ch, fp2). - 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 checksif (fptr1 != NULL). It also useschwithout declaring it as acharvariable first. These will cause compilation errors.