user1577409
user1577409

Reputation:

Copying binary file using write(), size of copied file increases

#include<fstream.h>
#include<conio.h>
#include<alloc.h>

class profile
{
   public: char *copyBytes;
}p;

void main()
{
   unsigned int size;

   fstream file ("file.mp3", ios::binary | ios::in | ios::out);
   fstream copy ("copy.mp3", ios::binary | ios::in | ios::out);
   file.seekg(0, ios::end);
   size=file.tellg();
   file.seekg(0);

   while(!file.eof())
   {
    p.copyBytes=(char*)malloc(size);
    file.read((char*)p.copyBytes, size);
    copy.write((char*)p.copyBytes, size);
    free(p.copyBytes);
   }

   file.close();

}

This program makes a copy of the binary file, file.mp3. The original binary file (file.mp3) is 2.13 MB and the copied file (copy.mp3) is 2.14 MB. Why?

Upvotes: 0

Views: 1059

Answers (1)

interjay
interjay

Reputation: 110154

  1. You never want to use a loop which looks like while (!file.eof()). Instead, check that the read operation succeeded, e.g. with:

    while (file.read(....))
    

    The eof flag might only be set by the next read operation, so checking it before reading is not helpful.

  2. You are always writing the full buffer to the output file, but read may read only a portion of the buffer. Use file.gcount() to see how many bytes were read.

Note that the buffer size doesn't need to be the same as the file size - that wouldn't work for files which don't fit in memory. You can simply use a constant size buffer. The loop will take care of copying the entire file.

Upvotes: 5

Related Questions