You should invest in fread
and fwrite
and let the underlying libraries and OS handle the looping:
// Reading size of file
FILE * file = fopen("input.txt", "r+");
if (file == NULL) return;
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
// Reading data to array of unsigned chars
file = fopen("input.txt", "r+");
unsigned char * in = (unsigned char *) malloc(size);
int bytes_read = fread(in, sizeof(unsigned char), size, file);
fclose(file);
file = fopen("output.txt", "w+");
int bytes_written = fwrite(out, sizeof(unsigned char), size, file);
fclose(file);
free(in);
If you want to perform an exact copy without any translations of the bytes, open the input file as "rb" and open the output file as "wb".
You should also consider using new
and delete[]
instead of malloc
and free
.