文本比较
需求描述
比较文本Test1.txt和Test2.txt,将两者的差异保存到新建文本Differences.txt中.
算法描述
通过文件操作以“只读”格式打开文本Test1.txt与Test2.txt,并新建文本Differences.txt,同时逐行读取两个已有文本并进行比较,如果不一致,则将两文本中的当前行保存到新建文本中并注明当前行,并且记录不一致的行数,最后保存到新建文本的最后。
Code
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//比较两个文本的差异
bool Compare()
{
int Row1 = 0; /*文本1的总行数*/
int Row2 = 0; /*文本2的总行数*/
int DifferRow = 0; /*两文本之间有差异的行数*/
/*以只读方式打开文本1并指向文件流fp1,若文本1不存在则产生错误*/
ifstream fp1("Test1.txt", ios::in);
/*以只读方式打开文本2指向文件流fp2,若文本2不存在则产生错误*/
ifstream fp2("Test2.txt", ios::in);
/*以写方式新建文本并指向文件流fp2,若文本已存在,则清空*/
ofstream fp3("Differences.txt", ios::out);
/*进行文件打开错误处理*/
if (!fp1.is_open())
{
cout << "File1 open failed!" << endl;
}
else if (!fp2.is_open())
{
cout << "File2 open failed!" << endl;
}
else if (!fp3.is_open())
{
cout << "Differ build Failed!" << endl;
}
else
{
string str1 = ""; /*用于临时存储从文本1中读取的数据*/
string str2 = ""; /*用于临时存储从文本2中读取的数据*/
fp3 << "有差异的行:" << endl;
/*逐行读取文本1并临时存到字符串str1*/
while (getline(fp1, str1))
{
/*逐行读取文本2并临时存到字符串str2*/
getline(fp2, str2);
Row1++;
Row2++;
/*比较字符串str1、str2,当两者不同时存入差异文本*/
if (str1 != str2)
{
DifferRow++; /*两文本有差异的行数加1*/
/*将差异存入差异文本*/
fp3 << "文本1第" << Row1 << "行:" << endl;
fp3 << str1 << endl;
/*当文本1的行数比文本2多时*/
if (str2.length() == 0)
{
Row2--;
fp3 << "文本2第" << Row2 << "行:" << "为空" << endl;
}
else
{
fp3 << "文本2第" << Row2 << "行:" << endl;
fp3 << str2 << endl;
}
}
}
/*当文本2的行数比文本1多时*/
while (getline(fp2, str2))
{
Row2++;
DifferRow++;
fp3 << "文本1第" << Row1 << "行:" << "为空" << endl;
fp3 << "文本2第" << Row2 << "行:" << endl;
fp3 << str2 << endl;
}
/*记录被比较文本总行数与不同行数*/
fp3 << "文本1共"<< Row1 << "行," << "文本2共" << Row2 << "行,"
<< "两文本有" << DifferRow <<
"行不同(行数较少的文本后面缺失的行数视为空行)" << endl;
}
/*关闭所有被打开文件*/
fp3.close();
fp2.close();
fp1.close();
/*当DifferRow>0时说明有差异*/
if (DifferRow > 0)
return false;
return true;
}
int main()
{
bool ans = Compare();
if (!ans)
cout << "两文本有差异!" << endl;
else
cout << "两文本无差异!" << endl;
return 0;
}