You are on page 1of 3

CSE1002 File Handling

Write a C program to merge contents of two files to


third file.
File 1
Learn C programming at VIT
Working with files and directories.
File 2
Learn C programming at VIT
Working with array and pointers.
Merge Two files (file1.txt and file2.txt in to newfile.txt)

Program to create two files:


// opening a file
#include <stdio.h>
int main() {
FILE *fpp;
fpp = fopen("file1.txt","w");
fprintf(fpp, "Learn C programming at VIT\n");
fprintf(fpp, "Working with array and pointers\n");
fclose(fpp);

fpp = fopen("file2.txt","w");
fprintf(fpp, "Learn C programming at VIT\n");
fprintf(fpp, "Working with files and directories.");
fclose(fpp);
}

Dr.Poongundran, SENSE, VIT, Vellore. Page 1


CSE1002 File Handling

Program to Merge two files:


/**
* C program to merge contents of two files to third file.
*/

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *sourceFile1,*sourceFile2, *destFile;
char sourcePath1[100],sourcePath2[100],destPath[100];

char ch;

/* Input path of files to merge to third file */


printf("Enter first source file path: ");
scanf("%s", sourcePath1); // user created file 1
printf("Enter second source file path: ");
scanf("%s", sourcePath2); // user created file 2
printf("Enter destination file path: ");
scanf("%s", destPath); // new file to store file 1 and file 2

/*
* Open source files in 'r' and
* destination file in 'w' mode
*/
sourceFile1 = fopen(sourcePath1, "r");
sourceFile2 = fopen(sourcePath2, "r");
destFile = fopen(destPath, "w");

Dr.Poongundran, SENSE, VIT, Vellore. Page 2


CSE1002 File Handling

/* fopen() return NULL if unable to open file in given mode. */


if (sourceFile1 == NULL || sourceFile2 == NULL || destFile ==
NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read/write
privilege.\n");

exit(EXIT_FAILURE);
}

/* Copy contents of first file to destination */


while ((ch = fgetc(sourceFile1)) != EOF)
fputc(ch, destFile);

/* Copy contents of second file to destination */


while ((ch = fgetc(sourceFile2)) != EOF)
fputc(ch, destFile);

printf("\nFiles merged successfully to '%s'.\n", destPath);

/* Close files to release resources */


fclose(sourceFile1);
fclose(sourceFile2);
fclose(destFile);

return 0;
}

Dr.Poongundran, SENSE, VIT, Vellore. Page 3

You might also like