Skip to main content

Copy contents of one file to another

Short answer

Open source file in read mode and destination in write mode, checking for NULL. Read characters with fgetc until EOF, writing each with fputc. Use int for the character to detect EOF. Close both files.

Write a program in C to copy content of one file source.txt to another destination.txt. (Read information of a file named "data.txt" and write its contents to another file "record.txt".)

Logic.

  1. Open the source file in read mode "r" and the destination in write mode "w", checking both for NULL.
  2. Read one character at a time with fgetc() until EOF and write it with fputc().
  3. Close both files.

The variable that holds the character is an int (not char), so that EOF can be detected correctly. The same program works for "data.txt" to "record.txt" by changing the two file names.

#include <stdio.h>

int main(void)
{
    FILE *src, *dst;
    int ch;

    src = fopen("source.txt", "r");
    if (src == NULL) {
        printf("Cannot open source.txt\n");
        return 1;
    }
    dst = fopen("destination.txt", "w");
    if (dst == NULL) {
        printf("Cannot create destination.txt\n");
        fclose(src);
        return 1;
    }
    while ((ch = fgetc(src)) != EOF)       /* read one character at a time */
        fputc(ch, dst);

    fclose(src);
    fclose(dst);
    printf("File copied successfully\n");
    return 0;
}

Sample run (source.txt has three lines; destination.txt has the same three lines afterwards)

File copied successfully

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →