kthouz
- 188
- 0
How can i use c program two merge two files. Does it have to do with "pointers" or am going wrong!
The discussion centers around merging two files using a C program. Participants explore various methods and functions, including the use of pointers, file handling functions like fopen, and system calls. The conversation includes both theoretical and practical aspects of file merging.
Participants express differing views on the necessity of pointers and the appropriateness of using system calls versus standard C functions. The discussion remains unresolved regarding the best approach to merging files.
Some participants note the importance of error checking in file operations, and there are references to specific platform-dependent functions that may affect portability.
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...