Reading binary file to unsigned char array and write it to another
Solution 1
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
.
Solution 2
This is not really answering your question about where the mistake is, but I think it's a much simpler way of writing from one binary file to another:
ifstream in(inputFile, ios::binary);
ofstream out(outputFile, ios::binary);
if(in.is_open() && out.is_open())
while(!in.eof())
out.put(in.get());
in.close();
out.close();
Alex Saskevich
Student, programmer, mod maker, I like to code and take part in interesting discussions and events.
Updated on July 09, 2022Comments
-
Alex Saskevich almost 2 years
Hello, I have some problem with rewriting files using C++. I try to read data from one binary file and write it to another.
{ // 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); for (int i = 0; i < size; i++) in[i] = fgetc(file); fclose(file); file = fopen("output.txt", "w+"); for (int i = 0; i < size; i++) fputc((int)in[i], file); fclose(file); free(in); }
But it write my buffer and also append some 0xFF bytes to the end of file (it append some bytes for small files, but can append some kilobytes for greater files). In what can be problem?
-
Admin about 10 yearsSame in one line: std::ofstream("destination.txt") << std::ifstream("source.txt").rdbuf();
-
Eutherpy about 10 yearsIn the spirit of C++... nice :)