我正在编写一个单元测试,需要将结果文件与黄金文件进行比较。最简单的方法是什么?
到目前为止我已经(对于Linux环境):
int result = system("diff file1 file2");
它们是不同的,如果result != 0
.
如果你想要一个纯 C++ 解决方案,我会这样做
#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);
}
它避免将整个文件读入内存,并在文件不同时(或在文件末尾)立即停止。 range_equal 因为std::equal
不为第二个范围采用一对迭代器,并且如果第二个范围较短则不安全。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)