If you're working with binary data, you do not want to 0-terminate the buffer, you just want to copy whatever you read right back out to the output stream. And you therefore don't want to use strlen on the output length side of things either.
A full example:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *input = "ohface.gif";
const char *output = "ohface_copy.gif";
FILE *in = fopen(input, "rb");
if (!in)
{
printf("Could not open %s for reading\n", input);
return 1;
}
FILE *out = fopen(output, "wb");
if (!out)
{
fclose(in);
printf("Could not open %s for writing\n", output);
return 1;
}
char buf[BUFSIZ] = { 0 };
size_t numRead = 0;
while ((numRead = fread(buf, 1, sizeof(buf), in)) != 0)
{
if (numRead == -1)
{
perror("Read error");
fclose(out);
fclose(in);
return 1;
}
if (fwrite(buf, 1, numRead, out) != numRead)
{
perror("Write error");
fclose(out);
fclose(in);
return 1;
}
}
fclose(out);
fclose(in);
return 0;
}
Code:
ls -l *.gif
-rw-r--r-- 1 rags staff 82445 Sep 18 15:14 ohface.gif
-rw-r--r-- 1 rags staff 82445 Sep 18 15:25 ohface_copy.gif