R05(2023)/10/29
R05(2023)/11/20(Swift のSource Code を追加しました。)
macOS Ventura
Xcode
ChatGPT3.5
C++
使用は自己責任でお願いします。
//
// main.cpp
// hashescompepara
//
// Created by niki on 2023/09/02.
//
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <thread>
// Function to compute the SHA-256 hash of a file
std::string calculateHash(const std::string& filePath, std::string& hash) {
std::string command = "shasum -a 256 " + filePath + " | awk '{print $1}'";
FILE* pipe = popen(command.c_str(), "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
hash = result;
return result;
}
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "Usage: " << argv[0] << " file1 file2" << std::endl;
return 1;
}
std::string file1 = argv[1];
std::string file2 = argv[2];
std::string hash1, hash2;
std::vector<std::thread> threads;
// Create two threads to calculate the hashes concurrently
threads.emplace_back([&]() { calculateHash(file1, hash1); });
threads.emplace_back([&]() { calculateHash(file2, hash2); });
// Wait for both threads to finish
for (auto& thread : threads) {
thread.join();
}
std::cout << "Hash 1: " << hash1 << std::endl;
std::cout << "Hash 2: " << hash2 << std::endl;
if (hash1 == hash2) {
std::cout << "Same" << std::endl;
} else {
std::cout << "Different" << std::endl;
}
return 0;
}
Swift のSource Code です。ChatGPT3.5 で作成しました。2 つのFile を同時に処理しているはずです。使用はは自己責任でお願いいたします。
import Foundation
// Function to compute the SHA-256 hash of a file
func calculateHash(filePath: String, completion: @escaping (String?) -> Void) {
let task = Process()
task.launchPath = "/usr/bin/shasum"
task.arguments = ["-a", "256", filePath]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = Pipe()
let fileHandle = pipe.fileHandleForReading
task.launch()
let data = fileHandle.readDataToEndOfFile()
let hash = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
let hashValue = hash?.components(separatedBy: " ").first // Extracting only the hash value
task.waitUntilExit()
completion(hashValue)
}
func main() {
let arguments = CommandLine.arguments
if arguments.count != 3 {
print("Usage: \(arguments[0]) file1 file2")
exit(1)
}
let file1 = arguments[1]
let file2 = arguments[2]
var hash1: String?
var hash2: String?
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
calculateHash(filePath: file1) { hash in
hash1 = hash
group.leave()
}
}
group.enter()
DispatchQueue.global().async {
calculateHash(filePath: file2) { hash in
hash2 = hash
group.leave()
}
}
// Main thread waits for the completion of asynchronous tasks
group.wait()
if let hash1 = hash1, let hash2 = hash2 {
print("Hash 1: \(hash1)")
print("Hash 2: \(hash2)")
if hash1 == hash2 {
print("Same")
} else {
print("Different")
}
} else {
print("Error calculating hashes")
}
}
main()