Adrian Popescu Adrian Popescu - 3 months ago 41
C++ Question

Ofstream writting too many bytes

I have some troubles when I want to write in file.
The main purpose of this program is to read all data from a exe file and after write it in another exe.
The problem is when I write the new file, it writes too many bites. For example I read 45568 (n=45568) bytes but in the new file I have 45800 bytes and i don't understand why.

#include <fstream>
#include <iostream>

int main(int argc, char** argv)
using namespace std;

ifstream file;"a.exe", istream::in | ios::binary);

std::streampos fsize = 0;
fsize = file.tellg();

file.seekg(0, std::ios::end);
fsize = file.tellg() - fsize;

int n = fsize;"a.exe", istream::in | ios::binary);
std::cout << n << " " << endl;

int z=0;
char *p = new char[n+1];
for (int i = 0;i < n;i++)
char ch;
p[i] = ch;
ofstream g;"b.bin");
std::cout << n;
g.write(p, n);

return 0;


Change this line:"b.bin");

To be this:"b.bin", istream::out | ios::binary);

On Windows (and legacy DOS, and many other legacy environments), files opened in text mode get special treatment for the end of line char: \n. When Windows writes a text mode file, all \n chars are written to file as \r followed by \n. Similarly, file reading in text mode converts \r\n sequences to \n. Opening files in binary mode turns off all this conversion behavior.

Also, your entire program can be simplified to:

void main(int argc, char** argv)
    ifstream in;
    ofstream out;"a.exe", istream::in | ios::binary);"b.bin", istream::out | ios::binary);

    while (in.rdstate() == in.goodbit)
        char c;
        if (in.get(c))
            out.write(&c, 1);