第一:读取为unsigned char*的数组然后写入文件
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc<3)
{
cout<<"参数错误"<<endl;
cout<<"<CMD> <FileNameSrc> <FileNameDis>"<<endl;
exit(-1);
}
int nFileSize=0;
//读出二进制文件的大小nFileSize
struct stat fFileMesg;
stat(argv[1],&fFileMesg);
cout<<fFileMesg.st_size<<endl;
nFileSize=fFileMesg.st_size;
//用二进制格式打开读写文件
ofstream ifs(argv[2],ios::binary);
ifstream ofs(argv[1],ios::binary);
if(!ifs)
{
cout<<"打开读取文件["<<argv[1]<<"]失败"<<endl;
system("PAUSE");
return -1;
}
if(!ofs)
{
cout<<"打开写入文件["<<argv[2]<<"]失败"<<endl;
system("PAUSE");
return -1;
}
//动态申请缓冲区,缓冲区大小为文件大小
unsigned char *NewBuffer=new unsigned char[nFileSize];
//把二进制文件流读写到缓冲区中
ofs.read((char *)NewBuffer, sizeof(char)*nFileSize);
//把缓冲区写入到文件中
ifs.write((char *)NewBuffer, sizeof(char)*nFileSize);
system("PAUSE");
//释放缓冲区和关闭文件流
ifs.close();
ofs.close();
delete NewBuffer;
return EXIT_SUCCESS;
}
第二:使用强制转换指针四个直接读取
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc<3)
{
cout<<"参数错误"<<endl;
cout<<"<CMD> <FileNameSrc> <FileNameDis>"<<endl;
exit(-1);
}
int nFileSize=0;
//读出二进制文件的大小nFileSize
struct stat fFileMesg;
stat(argv[1],&fFileMesg);
cout<<fFileMesg.st_size<<endl;
nFileSize=fFileMesg.st_size;
//用二进制格式打开读写文件
ofstream ifs(argv[2],ios::binary);
ifstream ofs(argv[1],ios::binary);
if(!ifs)
{
cout<<"打开读取文件["<<argv[1]<<"]失败"<<endl;
system("PAUSE");
return -1;
}
if(!ofs)
{
cout<<"打开写入文件["<<argv[2]<<"]失败"<<endl;
system("PAUSE");
return -1;
}
//使用int型强制转换四个字节四个字节读取
int nTmp=5;
int nCount=0;
while(!ofs.eof())
{
ofs.read((char*)(&nTmp), sizeof(nTmp));
//gcount()函数可以返回read读取的直接数
nCount+=ofs.gcount();
ifs.write((char*)(&nTmp), sizeof(nTmp));
}
//关闭文件流
ifs.close();
ofs.close();
system("PAUSE");
return EXIT_SUCCESS;
}