schneider
schneider

Reputation: 23

Ofstream writing 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;
    file.open("a.exe", istream::in | ios::binary);

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

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

    int n = fsize;
    file.open("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;
        file.get(ch);
        p[i] = ch;
    }
    file.close();
    ofstream g;
    g.open("b.bin");
    std::cout << n;
    g.write(p, n);

    return 0;
}

Upvotes: 0

Views: 763

Answers (1)

selbie
selbie

Reputation: 104539

Change this line:

g.open("b.bin");

To be this:

g.open("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;
    in.open("a.exe", istream::in | ios::binary);
    out.open("b.bin", istream::out | ios::binary);

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

Upvotes: 4

Related Questions