gpt4 book ai didi

c++ - 比较两个文件

转载 作者:可可西里 更新时间:2023-11-01 15:29:46 27 4
gpt4 key购买 nike

我正在尝试编写一个比较两个文件内容的函数。

如果文件相同,我希望它返回 1,如果不同,则返回 0。

ch1ch2 用作缓冲区,我使用 fgets 获取我的文件的内容。

我认为 eof 指针有问题,但我不确定。 FILE 变量在命令行中给出。

附言它适用于小于 64KB 的小文件,但不适用于较大的文件(例如 700MB 的电影,或 5MB 的 .mp3 文件)。

有什么想法,如何解决?

int compareFile(FILE* file_compared, FILE* file_checked)
{
bool diff = 0;
int N = 65536;
char* b1 = (char*) calloc (1, N+1);
char* b2 = (char*) calloc (1, N+1);
size_t s1, s2;

do {
s1 = fread(b1, 1, N, file_compared);
s2 = fread(b2, 1, N, file_checked);

if (s1 != s2 || memcmp(b1, b2, s1)) {
diff = 1;
break;
}
} while (!feof(file_compared) || !feof(file_checked));

free(b1);
free(b2);

if (diff) return 0;
else return 1;
}

编辑:我通过包含您的答案改进了此功能。但它只比较第一个缓冲区 -> 但有一个异常(exception) -> 我发现它停止读取文件,直到它达到 1A 字符(附加文件)。我们怎样才能让它发挥作用?

EDIT2:任务已解决(附有工作代码)。感谢大家的帮助!

最佳答案

如果你可以放弃一点速度,这里有一个需要很少代码的C++方式:

#include <fstream>
#include <iterator>
#include <string>
#include <algorithm>

bool compareFiles(const std::string& p1, const std::string& p2) {
std::ifstream f1(p1, std::ifstream::binary|std::ifstream::ate);
std::ifstream f2(p2, std::ifstream::binary|std::ifstream::ate);

if (f1.fail() || f2.fail()) {
return false; //file problem
}

if (f1.tellg() != f2.tellg()) {
return false; //size mismatch
}

//seek back to beginning and use std::equal to compare contents
f1.seekg(0, std::ifstream::beg);
f2.seekg(0, std::ifstream::beg);
return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(f2.rdbuf()));
}

通过使用 istreambuf_iterators,您可以将缓冲区大小选择、实际读取和对 eof 的跟踪推送到标准库实现中。 std::equal 在遇到第一个不匹配时返回,因此它不应运行超过它需要的时间。

这比 Linux 的 cmp 慢,但它很容易阅读。

关于c++ - 比较两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6163611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com