- #1
kthouz
- 193
- 0
How can i use c program two merge two files. Does it have to do with "pointers" or am going wrong!
FILE * fp;
fp = fopen("filename.txt", "wt");
fprintf(fp, "Hello fopen\n");
fclose(fp);
sunil bhatt said:Give the program to merge two files into a single one ic C Programming
morongo said:This is a somewhat 'tedious' but portable way to do it in C.
Opening the primary file for 'update' rather than 'append' has the effect of removing the EOF marker before appending new data.
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#ifdef BYTE
#undef BYTE
#endif
#define BYTE unsigned char
BYTE *buf2;
long size;
FILE *fp1, *fp2;
//open file-1 for update, file-2 for read
fp1=fopen(fname1,"a+");
fp2=fopen(fname2,"rb");
//get size of file-2
fseek(fp2,0,SEEK_END);
size=ftell(fp2);
rewind(fp2);
//allocate buffer, read-in file-2
buf2=(BYTE *)malloc((size_t)size);
fread(buf2,size,1,fp2);
//write the buffer to (end of) file-1
fwrite(buf2,size,1,fp1);
//clean-up and close
free(buf2);
fclose(fp1);
fclose(fp2);
It'd be a good idea to do some error checking if you use this code for anything serious...
To merge two files using a C program, you can use the fopen()
function to open both files, and then use the fgetc()
function to read characters from one file and write them to the other file using the fputc()
function.
The syntax for merging two files in C is as follows:
FILE *fp1, *fp2, *mergedFile;
fp1 = fopen("file1.txt", "r");
fp2 = fopen("file2.txt", "r");
mergedFile = fopen("merged_file.txt", "w");
int c;
while((c = fgetc(fp1)) != EOF)
{
fputc(c, mergedFile);
}
while((c = fgetc(fp2)) != EOF)
{
fputc(c, mergedFile);
}
fclose(fp1);
fclose(fp2);
fclose(mergedFile);
Yes, you can merge two files with different file extensions using the same method as merging two files with the same extension. The important thing is that both files can be opened and read by the fopen()
function.
Yes, it is possible to merge more than two files using a C program. You can use a similar approach as merging two files, but instead of using one fgetc()
and fputc()
function, you can use a loop to iterate through all the files and write the characters to the merged file.
You can check if the files have been successfully merged by opening the merged file in a text editor or using the fgetc()
function to read the merged file and print the characters to the console. If the merged file contains all the characters from both files, then the merge was successful.