Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //This program needs to be compiled at least with -std=c++17
- //Cause of <filesystem>, which provides cross-platform directories access
- #include <iostream>
- #include <filesystem>
- #include <fstream>
- #include <unordered_map>
- #include <algorithm>
- int main(int argc, const char* argv[])
- {
- struct file_amount
- {
- std::string filename;
- unsigned amount;
- };
- if (argc < 1)
- {
- std::cout << "Specify the directory to search files" << std::endl;
- return 0;
- }
- std::string path = argv[0];
- std::hash<std::string> hash_func;
- //key is the hash of the file contents, vector contains amount of files with that contents
- std::unordered_map<size_t, file_amount> occasions;
- for (const auto& file: std::filesystem::recursive_directory_iterator(path))
- {
- //open in binary to read bytes
- std::ifstream fin(file.path().string(), std::ios::binary);
- //the same thing as vector<char>, just stores bytes from file
- std::string bytes(std::istreambuf_iterator<char>{fin}, std::istreambuf_iterator<char>{});
- std::size_t file_hash = hash_func(std::move(bytes));
- fin.close();
- if (occasions.find(file_hash) != occasions.end())
- ++occasions[file_hash].amount;
- else
- occasions[file_hash] = {file.path().string(), 1};
- }
- file_amount max_copies = std::max_element(occasions.begin(), occasions.end(), [](const auto& a, const auto& b) {
- return a.second.amount < b.second.amount;
- })->second;
- std::cout << "File with maximum copies found: " << max_copies.filename << std::endl
- << "Found " << max_copies.amount << "copies" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment