我正在用 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
最佳答案
给定任意一对可同步文件 A
和 B
,只要两个文件的修改时间戳不相等,就需要同步.
问题是咳咳...时间戳不是 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);
}
编辑:您可能会看到 GetSystemTime() , SystemTimeToFileTime() , GetFileTime() ,和 SetFileTime()如果您需要使用Windows API。
关于c++ - 检查大量文件对是否相同的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494481/