Nếu bạn muốn có một c tinh khiết ++ giải pháp, tôi sẽ làm một cái gì đó như thế này
#include <algorithm>
#include <iterator>
#include <string>
#include <fstream>
template<typename InputIterator1, typename InputIterator2>
bool
range_equal(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2)
{
while(first1 != last1 && first2 != last2)
{
if(*first1 != *first2) return false;
++first1;
++first2;
}
return (first1 == last1) && (first2 == last2);
}
bool compare_files(const std::string& filename1, const std::string& filename2)
{
std::ifstream file1(filename1);
std::ifstream file2(filename2);
std::istreambuf_iterator<char> begin1(file1);
std::istreambuf_iterator<char> begin2(file2);
std::istreambuf_iterator<char> end;
return range_equal(begin1, end, begin2, end);
}
Nó tránh được đọc toàn bộ tập tin vào bộ nhớ, và dừng lại càng sớm càng các tập tin khác nhau (hoặc ở cuối của tập tin) . Phạm vi_equal vì std::equal
không mất một cặp vòng lặp cho phạm vi thứ hai và không an toàn nếu phạm vi thứ hai ngắn hơn.
Nguồn
2013-02-27 18:18:46
Điều đó nghe giống như một cách hợp lý để so sánh hai tệp, vâng. –
Có nhiều tùy chọn chuẩn khác nhau của 'diff' để triệt tiêu đầu ra. Sử dụng chúng, nếu bạn gọi nó thông qua 'hệ thống'. – pmr
Bạn có thể sử dụng 'cmp' thay vì' diff'. –