前言
这是很久以前实现的一个小功能,并不复杂,仅作记录,(QT 环境下)
比较函数
bool Widget::file_contrast(QString srcAbFilePath, QString destAbFilePath)
{
QString path_firstFile = QString(srcAbFilePath);
QString path_secondFile = QString(destAbFilePath);
QFile first_file(path_firstFile);
QFile second_file(path_secondFile);
bool first_open = false;
bool second_open = false;
qint64 first_file_size;
qint64 second_file_size;
qint64 first_read_size;
qint64 second_read_size;
char first_buff[4096];
char second_buff[4096];
memset(first_buff,0,sizeof(first_buff));
memset(second_buff,0,sizeof(second_buff));
first_open = first_file.open(QIODevice::ReadOnly);
second_open = second_file.open(QIODevice::ReadOnly);
if(first_open && second_open){
first_file_size = first_file.size();
second_file_size = second_file.size();
if(first_file_size == second_file_size){
qDebug() << "文件大小相同" << endl;
while(!first_file.atEnd() && !second_file.atEnd()){
first_read_size = first_file.read(first_buff,sizeof(first_buff));
second_read_size = second_file.read(second_buff,sizeof(second_buff));
if(first_read_size == second_read_size){
if(strcmp(first_buff,second_buff) == 0){
memset(first_buff,0,sizeof(first_buff));
memset(second_buff,0,sizeof(second_buff));
}
else{
qDebug() << "文件不相同" << endl;
first_file.close();
second_file.close();
return false;
}
}
else{
qDebug() << "读取大小不同" << endl;
first_file.close();
second_file.close();
return false;
}
}
qDebug() << "文件相同" << endl;
first_file.close();
second_file.close();
return true;
}
else{
qDebug() << "文件不相同" << endl;
first_file.close();
second_file.close();
return false;
}
}
else{
qDebug() << "文件不相同" << endl;
first_file.close();
second_file.close();
return false;
}
}
原理
函数参数是两个比较文件的路径.
比较只是单纯的比较了两个文件的大小,以及内容.
更简单的可以直接获取两个文件的哈希值,再进行哈希值对比.
注意
贴的这段代码可以用,但是写的很久了,一些书写规范及命名不是很专业,影响理解,抱歉.