Merge n files using a C program
- by Amal
I am writing a download Accelerator. So I download a file from the webserver into n parts. Now I want to merge the files into 1 single file. So I use the following code. And the file names are in the correct order. But the output file I am getting is different from the original download file. Can you tell me where could the error be ?C
int cbd_merge_files(const char** filenames, int n, const char* final_filename) {
FILE* fp = fopen(final_filename, "wb");
if (fp == NULL) return 1;
char buffer[4097];
for (int i = 0; i < n; ++i) {
const char* fname = filenames[i];
FILE* fp_read = fopen(fname, "rb");
if (fp_read == NULL) return 1;
int n;
while ((n = fread(buffer, sizeof(char), 4096, fp_read))) {
int k = fwrite(buffer, sizeof(char), n, fp);
if (!k) return 1;
}
fclose(fp_read);
}
fclose(fp);
return 0;
}