From bd0b4d123777f204b1b9380aca8bfd566014226a Mon Sep 17 00:00:00 2001 From: RybakovaSA Date: Tue, 27 May 2025 20:49:42 +0300 Subject: [PATCH] =?UTF-8?q?code:=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4=20curl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.cpp | 79 +++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 26 deletions(-) diff --git a/main.cpp b/main.cpp index 9548499..52735ac 100644 --- a/main.cpp +++ b/main.cpp @@ -1,9 +1,10 @@ -#include #include +#include +#include +#include #include "histogram.h" -#include "text.h" #include "svg.h" -#include +#include "text.h" using namespace std; @@ -12,39 +13,65 @@ struct Input { size_t bin_count{}; }; -Input input_data(istream& in_stream, bool prompt) { - Input in; +Input input_data(istream& in, bool prompt = false) { + Input in_data; size_t number_count; - - if (prompt) { - cerr << "Enter number count: "; - } - in_stream >> number_count; - - in.numbers.resize(number_count); - if (prompt && number_count > 0) { - cerr << "Enter numbers: "; - } + if (prompt) cerr << "Enter number count: "; + in >> number_count; + in_data.numbers.resize(number_count); + if (prompt && number_count > 0) cerr << "Enter numbers: "; for (size_t i = 0; i < number_count; i++) { - in_stream >> in.numbers[i]; + in >> in_data.numbers[i]; + } + if (prompt) cerr << "Enter bin count: "; + in >> in_data.bin_count; + return in_data; +} + +// Колбэк-функция для cURL: записывает данные в буфер +size_t write_data(void* ptr, size_t size, size_t nmemb, void* userdata) { + size_t total = size * nmemb; + stringstream* stream = reinterpret_cast(userdata); + stream->write(reinterpret_cast(ptr), total); + return total; +} + +Input download(const string& url) { + CURL* curl = curl_easy_init(); + if (!curl) { + cerr << "Failed to init curl" << endl; + exit(1); } - - if (prompt) { - cerr << "Enter bin count: "; + + stringstream buffer; + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); + + CURLcode res = curl_easy_perform(curl); + curl_easy_cleanup(curl); + + if (res != CURLE_OK) { + cerr << "cURL error: " << curl_easy_strerror(res) << endl; + exit(1); } - in_stream >> in.bin_count; - - return in; + + return input_data(buffer, false); } -int main() { +int main(int argc, char* argv[]) { curl_global_init(CURL_GLOBAL_ALL); - auto in = input_data(cin, true); - auto bins = make_histogram(in.numbers, in.bin_count); + Input input; + if (argc > 1) { + input = download(argv[1]); + } else { + input = input_data(cin, true); + } + + auto bins = make_histogram(input.numbers, input.bin_count); show_histogram_svg(bins); curl_global_cleanup(); - return 0; }