From 769fa2ee7549709d6103918f83f209d2524ec013 Mon Sep 17 00:00:00 2001 From: Zsombor Szabo-Antalovszky <zsombors@stud.ntnu.no> Date: Tue, 29 Apr 2025 02:36:47 +0200 Subject: [PATCH] added the cpp file for handling the snatch command --- snatch.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ snatch.h | 9 +++++++++ 2 files changed, 54 insertions(+) create mode 100644 snatch.cpp create mode 100644 snatch.h diff --git a/snatch.cpp b/snatch.cpp new file mode 100644 index 0000000..7e3a9b6 --- /dev/null +++ b/snatch.cpp @@ -0,0 +1,45 @@ +#include <iostream> +#include <fstream> +#include <curl/curl.h> +#include "snatch.h" + +using namespace std; + +// Write callback to write data into a file +size_t write_data(void* ptr, size_t size, size_t nmemb, FILE* stream) { + size_t written = fwrite(ptr, size, nmemb, stream); + return written; +} + +bool download_file(const string& url, const string& output_filename) { + CURL* curl; + FILE* fp; + CURLcode res; + + curl = curl_easy_init(); + if (curl) { + fp = fopen(output_filename.c_str(), "wb"); // "wb" = write binary + if (!fp) { + cerr << "Failed to open file: " << output_filename << endl; + curl_easy_cleanup(curl); + return false; + } + + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // Set the URL + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); // How to write received data + curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); // Where to write + res = curl_easy_perform(curl); // Perform download + + curl_easy_cleanup(curl); // Clean up + fclose(fp); // Close file + + if (res != CURLE_OK) { + cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl; + return false; + } + + return true; + } + return false; +} + diff --git a/snatch.h b/snatch.h new file mode 100644 index 0000000..d686f3b --- /dev/null +++ b/snatch.h @@ -0,0 +1,9 @@ +#ifndef __SNATCH_H +#define __SNATCH_H + +#include <iostream> + +size_t write_data(void* ptr, size_t size, size_t nmemb, FILE* stream); +bool download_file(const std::string& url, const std::string& output_filename); + +#endif \ No newline at end of file -- GitLab