比较两个文件是否相同的办法

  原本是朴素的遍历写法,后面改为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);  
}

 

posted @   ChebyshevTST  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示