C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Copy file contents

C Program: Copy contents from one file to another (file-to-file copy)

C

#include <stdio.h>

 

int main() {

    FILE *sourceFile, *targetFile;

    char source[100], target[100];

    char ch;

 

    // Step 1: Get file names

    printf("Enter source file name: ");

    scanf("%s", source);

 

    printf("Enter target file name: ");

    scanf("%s", target);

 

    // Step 2: Open source file for reading

    sourceFile = fopen(source, "r");

    if (sourceFile == NULL) {

        printf("Error! Cannot open source file.\n");

        return 1;

    }

 

    // Step 3: Open target file for writing

    targetFile = fopen(target, "w");

    if (targetFile == NULL) {

        printf("Error! Cannot open target file.\n");

        fclose(sourceFile);

        return 1;

    }

 

    // Step 4: Copy contents from source to target

    while ((ch = fgetc(sourceFile)) != EOF) {

        fputc(ch, targetFile);

    }

 

    printf("File copied successfully.\n");

 

    // Step 5: Close both files

    fclose(sourceFile);

    fclose(targetFile);

 

    return 0;

}

Output

 
INPUT :
Enter source file name: input.txt
Enter target file name: output.txt

CONSOLE OUTPUT :
File copied successfully.

File input.txt:

Welcome to C programming.
This file will be copied.

File output.txt (after execution):
Welcome to C programming.
This file will be copied.

Explanation

Step

Description

1

Takes input for the source and target file names.

2

Opens source file in read mode ("r").

3

Opens target file in write mode ("w") — creates if it doesn’t exist.

4

Reads one character at a time using fgetc() and writes it using fputc().

5

Closes both files properly.