linux下byte to byte 比较文件

#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;  
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值