diff --git a/snatch.cpp b/snatch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e3a9b65ab12821ca5801358c9a1e9293d215225 --- /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 0000000000000000000000000000000000000000..d686f3bb6f4492d5ebbbb42b2af6e018c21969a6 --- /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