原本是朴素的遍历写法,后面改为mmap后速度提升飞快(大部分时候一秒以内可以出结果)。可以用于比较两个文件内容是否相同,包括图片也可以(图片用open函数打开后是一堆乱码,相当于比较乱码)。Talk is cheap, show me your code。
#include <iostream>
#include <fstream>
#include <cstring>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
const int MAX_LEN = 200;
bool isSameFile(const char s1[], const char s2[]) {
int fd1 = open(s1, O_RDONLY);
int fd2 = open(s2, O_RDONLY);
if (fd1 == -1 || fd2 == -1) {
std::cerr << "An error happend!\n";
close(fd1);
close(fd2);
return false;
}
struct stat stat1, stat2;
if (fstat(fd1, &stat1) == -1 || fstat(fd2, &stat2) == -1) {
std::cerr << "Error getting file stats.\n";
close(fd1);
close(fd2);
return false;
}
if (stat1.st_size != stat2.st_size) {
close(fd1);
close(fd2);
return false;
}
char* map1 = static_cast<char*>(mmap(nullptr, stat1.st_size, PROT_READ, MAP_PRIVATE, fd1, 0));
char* map2 = static_cast<char*>(mmap(nullptr, stat2.st_size, PROT_READ, MAP_PRIVATE, fd2, 0));
if (map1 == MAP_FAILED || map2 == MAP_FAILED) {
std::cerr << "Error mapping files to memory.\n";
close(fd1);
close(fd2);
return false;
}
bool result = (memcmp(map1, map2, stat1.st_size) == 0);
munmap(map1, stat1.st_size);
munmap(map2, stat2.st_size);
close(fd1);
close(fd2);
return result;
}
int main() {
char ch1[MAX_LEN], ch2[MAX_LEN];
std::cin >> ch1 >> ch2;
std::cout << std::boolalpha;
std::cout << isSameFile(ch1, ch2);
}