Concatenate Two Files in C Programming
To concatenate two files in C, open both source files for reading, open a separate destination file for writing, and copy the contents of the first source followed by the contents of the second source. The resulting file contains the input data in the same order, without loading both files completely into memory.
File concatenation does not automatically insert a space, newline, comma, or other separator. If the first text file does not end with a newline, the first line from the second file may continue on the same line in the output.
Steps to merge two files into a third file in C
- Open the first and second source files with
fopen()in read mode. - Check that both source file pointers are not
NULL. - Open a third, distinct file in write mode.
- Read data from the first file and write it to the destination.
- Repeat the copy operation for the second file.
- Check for read and write errors.
- Close every successfully opened file with
fclose().
Opening the destination with "w" creates it if necessary and truncates it if it already exists. Do not use either source file as the destination because its original contents could be erased.
Character-by-character C program to concatenate two files
The following original example demonstrates the basic fgetc() and fputc() approach. It asks for two input filenames and an output filename, copies the first input, and then copies the second input.
C Program
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f1, *f2, *f3;
char ch, file1[30], file2[30], file3[30];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);
printf("Enter name of the output files\n");
gets(file3);
f1 = fopen(file1, "r"); //opening the file for reading.
f2 = fopen(file2, "r");
if(f1 == NULL || f2 == NULL) {
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
f3 = fopen(file3, "w"); // Opening in write mode
if(f3 == NULL) {
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(f1)) != EOF)
fputc(ch,f3);
while((ch = fgetc(f2)) != EOF)
fputc(ch,f3);
printf("The two files were merged into %s file successfully.\n", file3);
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
This older example illustrates the copy sequence, but new programs should not use gets(). That function cannot limit the number of characters written into the destination array and was removed from the C standard library in C11. Also, the result of fgetc() should be stored in an int, not a char, so that every possible byte value remains distinguishable from EOF.
Safer buffered C program for concatenating large files
The following program accepts filenames as command-line arguments and copies data in blocks with fread() and fwrite(). Its memory use remains bounded by the buffer size, so the source files do not need to fit in memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 16384
static int append_stream(FILE *source, FILE *destination) {
unsigned char buffer[BUFFER_SIZE];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof buffer, source)) > 0) {
if (fwrite(buffer, 1, bytes_read, destination) != bytes_read) {
return 0;
}
}
return !ferror(source);
}
int main(int argc, char *argv[]) {
FILE *first;
FILE *second;
FILE *output;
int success;
if (argc != 4) {
fprintf(stderr, "Usage: %s first_file second_file output_file\n", argv[0]);
return EXIT_FAILURE;
}
if (strcmp(argv[1], argv[3]) == 0 || strcmp(argv[2], argv[3]) == 0) {
fprintf(stderr, "The output filename must differ from both input filenames.\n");
return EXIT_FAILURE;
}
first = fopen(argv[1], "rb");
if (first == NULL) {
perror(argv[1]);
return EXIT_FAILURE;
}
second = fopen(argv[2], "rb");
if (second == NULL) {
perror(argv[2]);
fclose(first);
return EXIT_FAILURE;
}
output = fopen(argv[3], "wb");
if (output == NULL) {
perror(argv[3]);
fclose(first);
fclose(second);
return EXIT_FAILURE;
}
success = append_stream(first, output) &&
append_stream(second, output);
if (fclose(first) == EOF) {
success = 0;
}
if (fclose(second) == EOF) {
success = 0;
}
if (fclose(output) == EOF) {
success = 0;
}
if (!success) {
fprintf(stderr, "The files could not be concatenated completely.\n");
return EXIT_FAILURE;
}
printf("Created %s from %s and %s.\n", argv[3], argv[1], argv[2]);
return EXIT_SUCCESS;
}
The string comparison catches identical filename arguments. Before running the program, also make sure that differently written paths do not refer to the same underlying file, such as data.txt and ./data.txt.
Compile and run the C file concatenation program
If the buffered program is saved as merge_files.c, compile it with a C compiler such as GCC:
gcc -std=c11 -Wall -Wextra -pedantic merge_files.c -o merge_files
Pass the two source filenames first and the destination filename last:
./merge_files first.txt second.txt combined.txt
For example, if first.txt contains Red followed by a newline and second.txt contains Blue, the destination contains:
Red
Blue
Adding a separator between concatenated text files
A direct concatenation copies bytes exactly and adds nothing between the files. If the inputs are text files and a newline must separate them, write it after copying the first file and before copying the second:
if (!append_stream(first, output)) {
fprintf(stderr, "Could not copy the first file.\n");
return EXIT_FAILURE;
}
if (fputc('\n', output) == EOF) {
fprintf(stderr, "Could not write the separator.\n");
return EXIT_FAILURE;
}
if (!append_stream(second, output)) {
fprintf(stderr, "Could not copy the second file.\n");
return EXIT_FAILURE;
}
Only add a separator when the output format requires one. An unconditional newline changes the data and can create an extra blank line when the first file already ends with a newline.
Text mode and binary mode for C file concatenation
Use "r" and "w" when the program is intentionally processing text according to the platform’s text-stream rules. Use "rb" and "wb" when every byte must be preserved exactly.
On systems where text and binary modes differ, text mode can translate line endings or treat certain byte values specially. Binary mode is therefore the appropriate general choice for joining arbitrary file parts, images, archives, or other non-text data.
Handling errors while merging files in C
- Input file cannot be opened: Check the path, filename, permissions, and current working directory.
- Destination cannot be created: Check directory permissions, available storage, and whether the path names a directory.
- Output replaces an input: Require a separate destination and validate paths before opening it in write mode.
- Partial write: Compare the value returned by
fwrite()with the number of bytes requested. - Read failure: After the copy loop ends, use
ferror()to distinguish an error from the normal end of the file. - Close failure: Check
fclose()for the output stream because buffered data may fail to flush at that point. - Incomplete output: Do not report success when any read, write, or close operation fails.
Common mistakes in C file concatenation programs
- Using
gets()instead of bounded input or command-line arguments. - Storing the return value of
fgetc()incharinstead ofint. - Opening the destination before confirming that both input files can be opened.
- Using
"a"when the desired behavior is to replace an existing destination with a newly merged file. - Assuming that concatenation automatically inserts a newline between text files.
- Reading an entire large file into memory when a small reusable buffer is sufficient.
- Ignoring errors returned by
fread(),fwrite(),fputc(), orfclose().
C file concatenation FAQ
How do I concatenate two files in C?
Open both source files for reading and a third file for writing. Copy all data from the first source to the destination, then copy all data from the second source to the same destination. Check each file operation and close all three streams.
Can C concatenate files that are larger than available memory?
Yes. Process the inputs sequentially with fgetc() or, more efficiently, fixed-size blocks read by fread(). The buffered example uses a constant amount of working memory regardless of the total file sizes.
Does concatenating two text files add a newline between them?
No. A basic concatenation copies the source contents exactly. Write '\n' with fputc() between the two copy operations only when the output format requires a line break.
Should a C file-merging program use text mode or binary mode?
Use binary mode when bytes must remain unchanged or when the inputs are not plain text. Text mode is suitable when platform-specific text-stream processing is intentional. On some operating systems the modes behave identically, but portable code should still select the mode that matches the data.
C file concatenation editorial QA checklist
- Verify that the destination filename differs from both source filenames and does not resolve to the same underlying file.
- Test the program with empty files, files without trailing newlines, and files larger than the copy buffer.
- Confirm that binary test files match a direct byte-for-byte concatenation of the inputs.
- Check failure handling for a missing source, an unwritable destination, a full destination device, and a failed close operation.
- Compile the safer example with C11 warnings enabled and confirm that it produces no compiler diagnostics.
Summary of concatenating files with C file pointers
Concatenating files in C means copying each source stream to one destination stream in sequence. A buffered fread() and fwrite() implementation handles large files without allocating memory for their complete contents. The program should use a distinct output path, select the correct text or binary mode, and check every open, read, write, and close operation. Continue with the C Tutorial for additional file-handling examples.
TutorialKart.com