C PROGRAMMING PROGRAM • FILE HANDLING
Copy the Contents of One File to Another
Learn how to copy the contents of one file to another using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
File copied to destination.txt
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
FILE *source = fopen("source.txt", "w");
if (source == NULL) return 1;
fputs("CodeBhavya file-copy example.\n", source);
fclose(source);
source = fopen("source.txt", "rb");
FILE *destination = fopen("destination.txt", "wb");
if (source == NULL || destination == NULL) {
if (source != NULL) fclose(source);
if (destination != NULL) fclose(destination);
return 1;
}
int byte;
while ((byte = fgetc(source)) != EOF) fputc(byte, destination);
fclose(source);
fclose(destination);
printf("File copied to destination.txt\n");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
File copied to destination.txt
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Read each byte from the source and write it to the destination until EOF.
- Display the computed result.
Read each byte from the source and write it to the destination until EOF.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
