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;
}
C++读写二进制文件技巧
本文介绍如何使用C++的ifstream和ofstream类进行二进制文件的读写操作,通过示例代码展示了正确的文件打开模式和数据读写过程。
1317

被折叠的 条评论
为什么被折叠?



