You need to open the file in binary mode, as others have said, by doing
fstream fp1(argv[1], ios::in | ios::binary); // combine ios::in with ios::binary fstream fp2(argv[2], ios::out | ios::binary); // combine ios::out with ios::binary
Or you can make them ifstream
(read-only file stream) and ofstream
(file stream, write-only) and remove ios::in
and ios::out
, because ifstream
implies ios::in
and ofstream
means ios::out
:
ifstream fp1(argv[1], ios::binary); ofstream fp2(argv[2], ios::binary);
You need to do this because if you do not, the file will be translated when you read or write for it, for example, trim line endings from \r\n
or \r
only \n
, etc. which will corrupt your binary data, which these bytes can have in them.
It:
if (fp1.seekg (0, ios::beg)) return 0; if (fp2.seekg (0, ios::beg)) return 0;
It always returns code, because seekg
returns the object you call it on. This is not the equivalent of fseek
in this regard, because fseek
returns 0 on success. Therefore, you never end up in a while
. Derive them from if
so that they look like this:
fp1.seekg(0, ios::beg); fp2.seekg(0, ios::beg);
Or, if you have a check, you want to do
if (!fp1.seekg (0, ios::beg))
In addition, this (inside while
):
fp2.seekp(0);
Sets the point at which you are going to write to the beginning of the file. Therefore, you will never write anything except the beginning of the file. Just delete this line completely.
In addition, inside the loop there is return
, which returns it to the first iteration. Move return 1;
outside the loop, so that you will only return after the loop ends. Disregard this, incorrectly due to the unusual style of the brackets.