#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;
}
答案 0 :(得分:3)
更改此行:
g.open("b.bin");
要成为这样:
g.open("b.bin", istream::out | ios::binary);
在Windows(和旧版DOS,and many other legacy environments)上,以文本模式打开的文件会对行尾char:\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);
}
}
}