Reading binary file to unsigned char array and write it to another

25,438

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();
Share:
25,438
Alex Saskevich
Author by

Alex Saskevich

Student, programmer, mod maker, I like to code and take part in interesting discussions and events.

Updated on July 09, 2022

Comments

  • Alex Saskevich
    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
    Admin about 10 years
    Same in one line: std::ofstream("destination.txt") << std::ifstream("source.txt").rdbuf();
  • Eutherpy
    Eutherpy about 10 years
    In the spirit of C++... nice :)