您的位置:首页 > 运维架构 > Linux

linux下byte to byte 比较文件

2015-08-26 21:43 579 查看
#include <iostream>
#include <fstream>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <memory.h>

using namespace std;
#define SIZE 30
#define BLOCKSIZE 4096
char path1[SIZE];
char path2[SIZE];

size_t min(size_t a,size_t b)
{
return a<b?a:b;
}

void GetInput()
{
cout<<"Please enter two file names!"<<endl;
cout<<"file1: ";
cin>>path1;
while(access(path1,F_OK)!=0)
{
cout<<"The file you enter does not exist,please enter again!"<<endl;
cout<<"file1: ";
cin>>path1;
}
cout<<"file2: ";
cin>>path2;

while(access(path2,F_OK)!=0)
{
cout<<"The file you enter does not exist,please enter again!"<<endl;
cout<<"file2: ";
cin>>path2;
}

}

//byte to byte
bool compfile(ifstream& in1, ifstream& in2,size_t &position){
ifstream::pos_type size1, size2,difPosition;
size1 = in1.seekg(0, ifstream::end).tellg();
in1.seekg(0, ifstream::beg);
size2 = in2.seekg(0, ifstream::end).tellg();
in2.seekg(0, ifstream::beg);

size_t index = 0;
while(index <=size1 && index<=size2)
{
position=index;
char buffer1[BLOCKSIZE], buffer2[BLOCKSIZE];//BOLCKSIZE=4096
in1.read(buffer1, 1); //read 1 byte every time
in2.read(buffer2, 1);
if(0 != memcmp(buffer1, buffer2, 1))
return false;
index++;
}
if(size1!=size2) return false;
return true;
}

int main(int argc, char *argv[])
{
size_t position=0;
GetInput();
ifstream f1(path1);
ifstream f2(path2);
if (compfile(f1,f2,position))
cout<<"identical"<<endl;
else
{
cout<<"different"<<endl;
cout<<"The first location of difference: "<<position<<endl;
}
f1.close();
f2.close();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: