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.
📝 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:
- Ask for the source filename and the destination filename.
- Open the source in read mode (
"r"). - Open the destination in write mode (
"w"). This creates the file if it doesn't exist, or truncates it if it does. - Read one character at a time from the source with
fgetc(). - Write each character to the destination with
fputc(). - Close both files when
fgetcreturnsEOF.
💻 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:
source.txt:
Hello, World!This text will be copied.
File handling in C is fun!
Running the program:
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:
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. |
"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 withstrcmpfirst. - Missing
NULLchecks: If eitherfopenfails, subsequent reads/writes crash the program. - Leaking the source handle: If the destination fails to open,
fclose(src)must be called before returning. - Declaring
chaschar:fgetcreturnsint; usingcharmay fail to detectEOFon platforms wherecharis 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,fputcreturnsEOFbut 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/fputsis more efficient thanfgetc/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/chmodon Unix,GetFileAttributes/SetFileAttributeson Windows). - Compile with
gcc -Wall -Wextra -std=c11 -gto catch unused variables and format-string issues.