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.

IntermediateFILE pointerBinary-safe copyfgetc()/fputc()

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
File copied to destination.txt

COMPLETE C PROGRAM

Complete C implementation

copy-text-file.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

File copied to destination.txt
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Read each byte from the source and write it to the destination until EOF.
  3. 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.