检查大量文件对是否相同的快速方法

时间:2015-09-10 06:17:01

标签: c++ file compare

我正在用C ++构建一个小型同步实用程序,主要供个人使用。

想象一下,我们有两个目录'A'和'B'将被同步。在某些时候,A中的新文件必须复制到B.我到目前为止使用的逻辑是:

browse directory 'A'
for each 'A/afile'
    copy A/afile to B/afile
endfor
for each 'A/adirectory'
    recurse into 'A/adirectory'
endfor

这很好用,直到我注意到使用上面的方法,A中的所有文件都被复制到B.所以,如果A / afile和B / afile不同,我只想执行复制操作

所以,我的问题是,如何以快速和跨平台(希望)的方式比较它们?像计算每个文件的MD5校验和一样快吗?

关键是,由于文件比较可能是针对大量文件对进行的,因此我想要一些既可靠又快速的东西。而且,我认为“繁重且耗时”的任务应该是实际的复制操作,而不是文件检查。

PS。我也试图找到“技巧”,比如文件大小和修改时间,但没有成功。

修改

在考虑下面的答案后,我最终会检查这两个文件是否相同:

if optimize_speed then
      if A/afile is newer then no (cause A/afile is the 'source' file)
      if B/afile is newer then compare byte-to-byte and decide 
else
      compare byte-to-byte and decide
end

1 个答案:

答案 0 :(得分:2)

给定任意一对可同步文件AB,只要两个文件的修改时间戳相等,就需要同步。

问题是呃......时间戳不是C ++标准的一部分......所以,你需要使用像Boost / Qt这样的东西来实现跨平台目的。

另一种方式当然是忽略可移植性并采用POSIX解决方案(p.d:记得检查返回值!):

#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utime.h>

struct stat statOfA;
struct stat statOfB;
stat(pathOfA, &statOfA);
stat(pathOfB, &statOfB);

if(statOfA.st_mtime > statOfB.st_mtime) {
    // Sync! Then...
    struct timeval now;
    gettimeofday(&now, NULL);    // nullptr is prefered in C++11...

    struct timeval copys[] = { now, now };
    utimes(pathOfA, copys);
    utimes(pathOfB, copys);
}

修改:如果您需要使用Windows API,则可能会看到GetSystemTime()SystemTimeToFileTime()GetFileTime()SetFileTime()