The Wayback Machine - https://web.archive.org/web/20241109143330/https://www.geeksforgeeks.org/c-program-merge-contents-two-files-third-file/
Open In App

C Program to merge contents of two files into a third file

Last Updated : 07 Jul, 2017
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let the given two files be file1.txt and file2.txt. The following are steps to merge.
1) Open file1.txt and file2.txt in read mode.
2) Open file3.txt in write mode.
3) Run a loop to one by one copy characters of file1.txt to file3.txt.
4) Run a loop to one by one copy characters of file2.txt to file3.txt.
5) Close all files.

To successfully run the below program file1.txt and fil2.txt must exits in same folder.




#include <stdio.h>
#include <stdlib.h>
  
int main()
{
   // Open two files to be merged
   FILE *fp1 = fopen("file1.txt", "r");
   FILE *fp2 = fopen("file2.txt", "r");
  
   // Open file to store the result
   FILE *fp3 = fopen("file3.txt", "w");
   char c;
  
   if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
   {
         puts("Could not open files");
         exit(0);
   }
  
   // Copy contents of first file to file3.txt
   while ((c = fgetc(fp1)) != EOF)
      fputc(c, fp3);
  
   // Copy contents of second file to file3.txt
   while ((c = fgetc(fp2)) != EOF)
      fputc(c, fp3);
  
   printf("Merged file1.txt and file2.txt into file3.txt");
  
   fclose(fp1);
   fclose(fp2);
   fclose(fp3);
   return 0;
}


Output:

Merged file1.txt and file2.txt into file3.txt

Related Articles :


Previous Article
Next Article

Similar Reads

C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
Write a C program that displays contents of a given file like 'more' utility in Linux
Write a C program that displays contents of given line page by page. Given number of lines to show as 'n' at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on. We strongly recommend to minimize the browser and try this yourself first. We can open the given file and p
2 min read
Merge operations using STL in C++ | merge(), includes(), set_union(), set_intersection(), set_difference(), ., inplace_merge,
Some of the merge operation classes are provided in C++ STL under the header file "algorithm", which facilitates several merge operations in a easy manner. Some of them are mentioned below. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted containers and stores in new container in sorted order (merge sort). It takes 5 arguments
7 min read
C program to compare two files and report mismatches
We are given almost two identical files. But some characters are corrupted. We need to find the line number and their position where those corrupted letter exists as well as Total number of corrupted (error) letters. Examples: Input : file1.txt contains it is fun file2.txt contains it is run Output : Line Number : 2 Error Position : 1 Total Errors
2 min read
C Program to list all files and sub-directories in a directory
#include <stdio.h> #include <dirent.h> int main(void) { struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir("."); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf("Could not open current directory" ); return 0; } // Refer http://pu
1 min read
Linking Files having same variables with different data types in C
Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c. Note that none of the variables is declared as extern. What do you expect to be the output of the following command with given two programs? $ gcc -o my
2 min read
Multiple Source Files in C
C programming language, as it is a procedural programming language sometime we need two or more programs linked together to store all the methods together. So, let's check how to link two C source files. Methods to compile multi-file c program are given below: Methods to use two or more source code files in C There are two methods to use two or mor
3 min read
What’s difference between header files "stdio.h" and "stdlib.h" ?
These are two important header files used in C programming. While “<stdio.h>” is header file for Standard Input Output, “<stdlib.h>” is header file for Standard Library. One easy way to differentiate these two header files is that “<stdio.h>” contains declaration of printf() and scanf() while “<stdlib.h>” contains declaratio
2 min read
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive "#include". C Header files offer the features like library functions, data types, macros, etc by importing them int
7 min read
C program to delete a file
The remove() function in C/C++ can be used to delete a file. The function returns 0 if the file is deleted successfully, Otherwise, it returns a non-zero value. The remove() is defined inside the <stdio.h> header file. Syntax of remove()remove("filename");ParametersThis function takes a string as a parameter, which represents the name of the
2 min read
LEX program to add line numbers to a given file
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Example: Input: #include<stdio.h> // Driver Code int
2 min read
C Program to count the Number of Characters in a File
Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is
2 min read
C Program to count number of lines in a file
C/C++ Code /* C Program to count the Number of Lines in a Text File */ #include <stdio.h> #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete p
1 min read
C++ program to print unique words in a file
Write a function that takes a file name as argument and prints all unique words in it. We strongly recommend you to minimize your browser and try this yourself first The idea is to use map in STL to keep track of words already occurred. C/C++ Code // C++ program to print unique words in a string #include <bits/stdc++.h> using namespace std; /
2 min read
Encode an ASCII string into Base-64 Format
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML. Problem with sending normal binary data to a network is th
15+ min read
C | File Handling | Question 1
Which of the following true about FILE *fp (A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type (C) FILE is a stream (D) FILE is a buffered stream Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store followin
1 min read
C | File Handling | Question 2
When fopen() is not able to open a file, it returns (A) EOF (B) NULL (C) Runtime Error (D) Compiler Dependent Answer: (B) Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.Quiz of this Question
1 min read
C | File Handling | Question 3
getc() returns EOF when (A) End of files is reached (B) When getc() fails to read a character (C) Both of the above (D) None of the above Answer: (C) Explanation: See EOF, getc() and feof() in CQuiz of this Question
1 min read
C | File Handling | Question 4
In fopen(), the open mode "wx" is sometimes preferred "w" because. 1) Use of wx is more efficient. 2) If w is used, old contents of file are erased and a new empty file is created. When wx is used, fopen() returns NULL if file already exists. (A) Only 1 (B) Only 2 (C) Both 1 and 2 (D) Neither 1 nor 2 Answer: (B) Explanation: See https://www.geeksfo
1 min read
C | File Handling | Question 5
fseek() should be preferred over rewind() mainly because (A) rewind() doesn't work for empty files (B) rewind() may fail for large files (C) In rewind, there is no way to check if the operations completed successfully (D) All of the above Answer: (C) Explanation: Please see fseek() vs rewind() in CQuiz of this Question
1 min read
Difference between Header file and Library
Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi
3 min read
What is data type of FILE in C ?
Prerequisite : Basics of File Handling In C language, while file handling is done a word FILE is used. What is FILE? Example FILE *fp1, *fp2; While doing file handling we often use FILE for declaring the pointer in order to point to the file we want to read from or to write on. As we are declaring the pointer of type FILE so we can say it is data t
3 min read
LEX code to extract HTML tags from a file
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Approach: The extraction is based on the way tags are w
1 min read
Bank account system in C using File handling
This article focuses on how to create a bank account system using C language and File handling in C. Approach:Let's discuss the approach in detail, covering all the functions and their explanation in detail- Create a Menu in the main function and create different functions for the Menu, which will be called using switch case statements. There are f
12 min read
ATM using file handling in C++
In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. File handling: File handling is used to store the output of a program in a file.In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling. Some Important Instruct
6 min read
cJSON - JSON File Write/Read/Modify in C
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using
6 min read
C File Pointer
A file pointer is a variable that is used to refer to an opened file in a C program. The file pointer is actually a structure that stores the file data such as the file name, its location, mode, and the current position in the file. It is used in almost all the file operations in C such as opening, closing, reading, writing, etc. SyntaxFILE *ptr; H
3 min read
fopen() for an existing file in write mode
In C, fopen() is used to open a file in different modes. To open a file in write mode, "w" is specified. When mode "w" is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the
2 min read
Comment in header file name?
What happens if there is a comment in header file name? Parsing of `#include' is slightly special because comments are not recognized within the ''. Thus, in `#include ' the `/*' does not start a comment and the directive specifies inclusion of a system header file named `x/*y'. Of course, a header file with such a name is unlikely to exist on Unix
1 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
Article Tags :
three90RightbarBannerImg