From 36d8e3c870127c0bdc6b56fdbba634e1535a5ce1 Mon Sep 17 00:00:00 2001 From: Isaac0-dev <62234577+Isaac0-dev@users.noreply.github.com> Date: Tue, 22 Apr 2025 13:10:27 +1000 Subject: [PATCH] upload hash_file.cpp --- tools/hash_file.cpp | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 tools/hash_file.cpp diff --git a/tools/hash_file.cpp b/tools/hash_file.cpp new file mode 100644 index 000000000..79d0706c5 --- /dev/null +++ b/tools/hash_file.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include +#include + +static std::string readFileData(const std::string &filepath) { + if (filepath == "") { return ""; } + std::ifstream file(filepath, std::ios::binary | std::ios::ate); + if (!file) throw std::runtime_error("Cannot open file."); + std::streamsize fileSize = file.tellg(); + file.seekg(0, std::ios::beg); + std::string data(fileSize, '\0'); + if (!file.read(&data[0], fileSize)) throw std::runtime_error("Cannot read file data."); + return data; +} + +std::size_t hashFile(const std::string &filepath) { + const std::string data = readFileData(filepath); + if (data == "") { return 0; } + return std::hash{}(data); +} + +int main(int argc, char *argv[]) { + if (argc != 2) { + std::cerr << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + + std::string filepath = argv[1]; + + try { + if (!std::filesystem::exists(filepath)) { + std::cerr << "Error: File does not exist." << std::endl; + return 1; + } + + std::size_t fileHash = hashFile(filepath); + std::cout << "Hash of file '" << filepath << "': " + << fileHash << " :: " + << std::hex << std::uppercase << std::showbase << fileHash + << std::endl; + } catch (const std::exception &e) { + std::cerr << "Error: " << e.what() << std::endl; + return 1; + } + + return 0; +}