-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathText_File_Compare.cpp
99 lines (88 loc) · 2.51 KB
/
Text_File_Compare.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cctype> // For isspace
// Function to remove whitespace characters from a string
std::string removeWhitespace(const std::string &str)
{
std::string result;
for (char c : str)
{
if (!std::isspace(static_cast<unsigned char>(c)))
{
result += c;
}
}
return result;
}
void compareFiles(const std::string &file1, const std::string &file2)
{
std::ifstream fileStream1(file1);
std::ifstream fileStream2(file2);
if (!fileStream1.is_open()&&!fileStream2.is_open())
{
std::cerr << "Unable to open both files." << std::endl;
return;
}
if (!fileStream1.is_open())
{
std::cerr << "Unable to open first file." << std::endl;
return;
}
if (!fileStream2.is_open())
{
std::cerr << "Unable to open second file." << std::endl;
return;
}
std::string line1, line2;
int lineNum = 1;
bool filesAreEqual = true;
while (std::getline(fileStream1, line1) && std::getline(fileStream2, line2))
{
// Remove whitespace from lines before comparing
std::string trimmedLine1 = removeWhitespace(line1);
std::string trimmedLine2 = removeWhitespace(line2);
if (trimmedLine1 != trimmedLine2)
{
std::cout << "Files differ at line " << lineNum << std::endl;
filesAreEqual = false;
}
lineNum++;
}
// If one file has more lines than the other
while (std::getline(fileStream1, line1))
{
std::string trimmedLine1 = removeWhitespace(line1);
if (!trimmedLine1.empty())
{
std::cout << "File 2 is shorter, difference at line " << lineNum << std::endl;
filesAreEqual = false;
}
lineNum++;
}
while (std::getline(fileStream2, line2))
{
std::string trimmedLine2 = removeWhitespace(line2);
if (!trimmedLine2.empty())
{
std::cout << "File 1 is shorter, difference at line " << lineNum << std::endl;
filesAreEqual = false;
}
lineNum++;
}
if (filesAreEqual)
{
std::cout << "Files are identical." << std::endl;
}
}
int main()
{
std::string filename1, filename2;
std::cout << "Enter path to the first file: ";
std::getline(std::cin, filename1);
std::cout << "Enter path to the second file: ";
std::getline(std::cin, filename2);
compareFiles(filename1, filename2);
return 0;
}