C Program to Merge Contents of Two Files into a Third File

C Program to Merge Contents of Two Files into a Third File

Merging the contents of two files into a third file is a common task in file handling. In this tutorial, we will use the C Standard Library functions provided by <stdio.h> to achieve this.

1. Setup

Ensure you include the necessary header file:

#include <stdio.h> 

2. The Process

Here's a step-by-step breakdown of the process:

  1. Open the first file in read mode.
  2. Open the second file in read mode.
  3. Create (or open, if it exists) the third file in write mode.
  4. Read contents from the first file and write to the third file.
  5. Read contents from the second file and write to the third file.
  6. Close all files.

3. Example: C Program to Merge Contents

#include <stdio.h> int main() { FILE *file1, *file2, *file3; char ch; // Open first file in read mode file1 = fopen("file1.txt", "r"); if (file1 == NULL) { perror("Error opening file1.txt"); return 1; } // Open second file in read mode file2 = fopen("file2.txt", "r"); if (file2 == NULL) { perror("Error opening file2.txt"); fclose(file1); // Close the already opened file1 return 1; } // Open third file in write mode file3 = fopen("merged.txt", "w"); if (file3 == NULL) { perror("Error opening merged.txt"); fclose(file1); // Close file1 fclose(file2); // Close file2 return 1; } // Read contents from file1 and write to file3 while ((ch = fgetc(file1)) != EOF) { fputc(ch, file3); } // Read contents from file2 and write to file3 while ((ch = fgetc(file2)) != EOF) { fputc(ch, file3); } printf("Contents merged successfully into merged.txt.\n"); // Close all files fclose(file1); fclose(file2); fclose(file3); return 0; } 

Things to Consider:

  • Always check if files are opened successfully by checking for a NULL return from the fopen() function.
  • Use the perror() function to get a specific reason for file-related errors.
  • Always ensure you close files after you're done with them using fclose(). This releases the resources associated with the file.
  • Be cautious when writing to files. If the third file (merged.txt in our example) already exists, its content will be overwritten.
  • You can adjust this logic to append contents instead of overwriting by opening the third file in append mode ("a" mode with fopen()).

More Tags

backslash windows-container setstate ansi-c azure-devops-rest-api orders iokit browser onsubmit android-4.0-ice-cream-sandwich

More Programming Guides

Other Guides

More Programming Examples