Ofstream 写入太多字节

Ofstream writing too many bytes

我想写入文件时遇到了一些麻烦。 该程序的主要目的是从一个 exe 文件中读取所有数据,然后将其写入另一个 exe。 问题是当我写新文件时,它写的太多了。例如,我读取了 45568 (n=45568) 字节,但在新文件中我有 45800 字节,我不明白为什么。

#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;
}

更改此行:

g.open("b.bin");

变成这样:

g.open("b.bin", istream::out | ios::binary);

在 Windows(和传统 DOS,and many other legacy environments)上,以文本模式打开的文件对行尾字符进行特殊处理:\n。当 Windows 写入文本模式文件时,所有 \n 个字符都写入文件,如 \r 后跟 \n。类似地,以文本模式读取文件会将 \r\n 序列转换为 \n。以二进制模式打开文件会关闭所有这些转换行为。

此外,您的整个程序可以简化为:

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);
        }
    }
}