Merge n files using a C program

Posted by Amal on Stack Overflow See other posts from Stack Overflow or by Amal
Published on 2012-07-08T14:51:45Z Indexed on 2012/07/08 15:16 UTC
Read the original article Hit count: 195

Filed under:

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;
}

© Stack Overflow or respective owner

Related posts about c