Skip to content

Instantly share code, notes, and snippets.

@Vinnik67
Created April 4, 2026 16:01
Show Gist options
  • Select an option

  • Save Vinnik67/4883116dcffdd13c6bb5a23208f8f5cd to your computer and use it in GitHub Desktop.

Select an option

Save Vinnik67/4883116dcffdd13c6bb5a23208f8f5cd to your computer and use it in GitHub Desktop.
#include <iostream>
#include <conio.h> // для _getch()
#include <curl/curl.h>
#include <fstream>
#include <filesystem>
#include <string>
#include <ctime>
// Функція для запису даних у файл
size_t write_data(void* ptr, size_t size, size_t nmemb, void* stream) {
std::ofstream* out = static_cast<std::ofstream*>(stream);
out->write(static_cast<char*>(ptr), size * nmemb);
return size * nmemb;
}
// Генерація унікального імені файлу
std::string generateFilename(const std::string& folder, const std::string& prefix) {
std::time_t t = std::time(nullptr);
char buf[64];
std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", std::localtime(&t));
return folder + "/" + prefix + "_" + buf + ".jpg";
}
// Завантаження файлу з URL
void downloadFile(const std::string& url, const std::string& filename) {
CURL* curl = curl_easy_init();
if (curl) {
std::ofstream file(filename, std::ios::binary);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &file);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // слідувати редіректам
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
std::cout << "Файл успішно завантажено: " << filename << std::endl;
}
else {
std::cerr << "Помилка завантаження: " << curl_easy_strerror(res) << std::endl;
}
curl_easy_cleanup(curl);
}
}
int main() {
std::string folder = "downloads";
std::filesystem::create_directories(folder);
std::cout << "Натисни пробіл для завантаження котика, ESC для виходу...\n";
while (true) {
int ch = _getch();
if (ch == 27) break; // ESC
if (ch == 32) { // Space
std::string filename = generateFilename(folder, "cat");
downloadFile("https://placekitten.com/800/600", filename);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment