Copy One Text File to Another — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Copy the Contents of One Text File into Another Text File

In this tutorial, you'll learn how to copy the contents of one text file into another text file using the C programming language. This is the classic "file copy" program — the C equivalent of cp source dest on Unix or copy source dest on Windows. The program opens the source in read mode and the destination in write mode, then reads one character at a time from the source and writes it to the destination. It's the simplest file-processing loop you can write, and it forms the basis of nearly every other file-handling program.

C program to copy the contents of one text file into another using fopen, fgetc, and fputc, with step-by-step explanation.

📝 Problem Statement

Write a program in C to copy the contents of one text file into another text file.

⚙️ How the Program Works

The program follows a straightforward read-write loop:

  1. Ask for the source filename and the destination filename.
  2. Open the source in read mode ("r").
  3. Open the destination in write mode ("w"). This creates the file if it doesn't exist, or truncates it if it does.
  4. Read one character at a time from the source with fgetc().
  5. Write each character to the destination with fputc().
  6. Close both files when fgetc returns EOF.

💻 Complete C Program

#include <stdio.h> int main(void) { FILE *src, *dst; char src_name[100]; char dst_name[100]; int ch; long count = 0; printf("Enter the source filename: "); scanf("%99s", src_name); printf("Enter the destination filename: "); scanf("%99s", dst_name); /* Open source in read mode */ src = fopen(src_name, "r"); if (src == NULL) { printf("Error: Could not open '%s'.\n", src_name); return 1; } /* Open destination in write mode (creates or truncates) */ dst = fopen(dst_name, "w"); if (dst == NULL) { printf("Error: Could not create '%s'.\n", dst_name); fclose(src); return 1; } /* Read one byte at a time and write it to the destination */ while ((ch = fgetc(src)) != EOF) { fputc(ch, dst); count++; } fclose(src); fclose(dst); printf("Copied %ld bytes from '%s' to '%s'.\n", count, src_name, dst_name); return 0; }

🖥️ Sample Output

Assume source.txt contains a short message:

Contents of source.txt: Hello, World!
This text will be copied.
File handling in C is fun!

Running the program:

Console: Enter the source filename: source.txt
Enter the destination filename: destination.txt
Copied 62 bytes from 'source.txt' to 'destination.txt'.

After the program finishes, destination.txt is an exact duplicate of source.txt:

Contents of destination.txt: Hello, World!
This text will be copied.
File handling in C is fun!

🔍 Line-by-Line Explanation

Line / Code Explanation
char src_name[100], dst_name[100]; Buffers to hold the two filenames.
scanf("%99s", src_name) Reads the source filename without spaces. %99s limits the input to 99 characters to avoid overflow.
fopen(src_name, "r") Opens the source file in read mode. Returns NULL if the file doesn't exist or cannot be read.
fopen(dst_name, "w") Opens the destination in write mode. Creates the file if it doesn't exist, truncates it if it does. This is why copying to an existing file overwrites it.
if (dst == NULL) { fclose(src); return 1; } If the destination can't be opened, close the source before returning to avoid a file-handle leak.
while ((ch = fgetc(src)) != EOF) Reads one byte at a time. fgetc returns int so EOF (-1) can be distinguished from a byte value of 0xFF.
fputc(ch, dst) Writes the byte to the destination. Bytes that aren't printable (e.g., \n) are written exactly as-is.
fclose(src); fclose(dst); Flushes buffers and releases both handles. The destination is only guaranteed to be fully written after fclose.
⚠️ Important: The destination is opened with "w", which truncates any existing file. If you accidentally use the source name for both files, you'll wipe the file before reading it. Add a check like strcmp(src_name, dst_name) != 0 to prevent this.

🔁 Other Ways to Copy a File

The byte-by-byte loop is the most portable approach, but C offers a few alternatives, each with its own trade-offs:

Approach Best for Trade-off
fgetc / fputc loop Portable, simple, handles all files Slowest — one system call per byte (though buffering hides most of this)
fgets / fputs line loop Text files with reasonable line lengths Requires a buffer; longer lines are processed in chunks
fread / fwrite block copy Large files, binary files Need a buffer (e.g., 4–64 KB); most efficient of the three

Here's the block-copy version, which is typically 10–100× faster for large files:

#define BUFSIZE (16 * 1024) int copy_file(const char *src_name, const char *dst_name) { FILE *src = fopen(src_name, "rb"); if (!src) return -1; FILE *dst = fopen(dst_name, "wb"); if (!dst) { fclose(src); return -1; } char buf[BUFSIZE]; size_t n; while ((n = fread(buf, 1, BUFSIZE, src)) > 0) fwrite(buf, 1, n, dst); fclose(src); fclose(dst); return 0; }

This version uses binary mode, so it works for text files, images, executables — anything. The buffer size of 16 KB matches the disk block size on most systems, minimizing read/write overhead.

🐛 Common Pitfalls

  • Using the same filename for source and destination: Opening the destination in "w" mode truncates the file before you read from it, so you copy an empty file. Check with strcmp first.
  • Missing NULL checks: If either fopen fails, subsequent reads/writes crash the program.
  • Leaking the source handle: If the destination fails to open, fclose(src) must be called before returning.
  • Declaring ch as char: fgetc returns int; using char may fail to detect EOF on platforms where char is unsigned.
  • Text mode for binary files: Copying an image or executable with "r"/"w" on Windows can corrupt it because of line-ending translation. Use "rb"/"wb" for anything that isn't pure text.
  • Ignoring fputc's return value: If the disk is full, fputc returns EOF but the loop keeps going. Check the return value in production code.

💡 Tips & Best Practices

  • For text files with lines shorter than a few KB, fgets/fputs is more efficient than fgetc/fputc.
  • For anything larger than a few MB, use the block-copy version with fread/fwrite.
  • Always close the destination before checking that the copy succeeded — buffered writes reach disk only at fclose.
  • If you want to preserve file permissions or timestamps, you'll need platform-specific APIs (stat/chmod on Unix, GetFileAttributes/SetFileAttributes on Windows).
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch unused variables and format-string issues.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 1. Create a New Text File and Write Text in It
  • 4. Read and Display the Contents of a Text File
  • 9. Merge Multiple Text Files into a Single Text File
  • 14. Append Text to an Existing Text File
  • Binary Files in C — Overview
  • Files FAQ

Previous Problem: -->> 14. Append Text to an Existing Text File   ||   Next Problem: -->> 16. Store and Retrieve Student Records Using Structures and Binary Files

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.