第一:讀取為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;
}