C++语言读写二进制文件应该使用ifstream和ofstream类,文件的打开模式一定要是binary。下面直接上代码吧。
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
const int LEN = 1024*1024;
char buf[LEN];
ifstream fin("demo1.pdf", ifstream::in | ifstream::binary);
ofstream fout("demo2.pdf", ofstream::out | ofstream::binary);
if(!fin || !fout)
{
cerr << "File Error" << endl;
return EXIT_FAILURE;
}
while(fin.read(buf, LEN))
{
fout.write(buf, LEN);
}
fout.write(buf, fin.gcount());
return EXIT_SUCCESS;
}