-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduplicate_detector.cpp
More file actions
101 lines (88 loc) · 2.65 KB
/
duplicate_detector.cpp
File metadata and controls
101 lines (88 loc) · 2.65 KB
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
100
101
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <vector>
#include <filesystem>
#include <cstdio>
#include <algorithm>
namespace fs = std::filesystem;
std::string getUrl(fs::path &filepath){
std::ifstream inFile(filepath);
if (!inFile.is_open()){
return "";
}
std::string line;
std::getline(inFile, line);
std::string before = "URL: ";
std::string after = " Doc number:";
size_t s = line.find(before);
if (s == std::string::npos){
return "";
}
s += before.size();
size_t e = line.find(after, s);
if (e == std::string::npos){
return "";
}
return line.substr(s, e - s);
}
int main(int argc, char* argv[]){
if (argc < 2){
std::cerr << "Expected: " << argv[0] << " [-d] <directory_path>\n";
return 1;
}
bool shouldDelete = false;
std::string dirpath;
if (std::string(argv[1]) == "-d") {
if (argc < 3) {
std::cerr << "No directory after -d\n";
return 1;
}
shouldDelete = true;
dirpath = argv[2];
} else {
dirpath = argv[1];
}
std::unordered_map<std::string, std::vector<std::string>> urlToFiles;
size_t total = 0;
for (auto &entry : fs::directory_iterator(dirpath)) {
auto path = entry.path();
if (path.extension() == ".parsed") {
std::string url = getUrl(path);
if (!url.empty()){
urlToFiles[url].push_back(path.filename().string());
total++;
}
}
}
size_t numRemoved = 0;
size_t duplicates = 0;
for (auto &pair : urlToFiles) {
const std::string &url = pair.first;
std::vector<std::string> &vec = pair.second;
std::cout << url << ":\n";
for (auto &f : vec) {
std::cout << " -> " << f << "\n";
}
duplicates+=vec.size()-1;
if (shouldDelete && vec.size() > 1) {
for (size_t i = 1; i < vec.size(); i++){
std::string fullpath = (fs::path(dirpath) / vec[i]).string();
if (std::remove(fullpath.c_str()) == 0) {
numRemoved++;
}
else {
std::perror(("Error removing file " + fullpath).c_str());
}
}
}
}
std::cout << "Number of duplicates: " << duplicates << "\n";
if (shouldDelete) {
std::cout << "\nOriginal document count: " << total << "\n"
<< "Documents removed: " << numRemoved << "\n"
<< "Final document count: " << (total - numRemoved) << "\n";
}
return 0;
}