Skip to content

Instantly share code, notes, and snippets.

@641i130
Created September 20, 2023 16:06
Show Gist options
  • Save 641i130/c0ef27b1b0fe3855d90294cc47d51c4c to your computer and use it in GitHub Desktop.
Save 641i130/c0ef27b1b0fe3855d90294cc47d51c4c to your computer and use it in GitHub Desktop.
Simple curl download example
#include <iostream>
#include <fstream>
#include <curl/curl.h>
// g++ -o test test.cpp -lcurl
// Callback function to write data to a file
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
size_t totalSize = size * nmemb;
std::ofstream* fileStream = static_cast<std::ofstream*>(userp);
if (fileStream)
{
fileStream->write(static_cast<const char*>(contents), totalSize);
return totalSize;
}
return 0;
}
int main()
{
CURL* curl;
CURLcode res;
// URL to download
const char* url = "https://caret.rs/";
// Output file name
const char* outputFile = "downloaded.html";
// Initialize libcurl
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl)
{
// Create or open a file to write the downloaded data
std::ofstream file(outputFile, std::ios::binary);
// Set the URL to download
curl_easy_setopt(curl, CURLOPT_URL, url);
// Set the callback function to write data to the file
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &file);
// Perform the HTTP request and download
res = curl_easy_perform(curl);
// Check for errors
if (res != CURLE_OK)
{
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else
{
std::cout << "Download successful." << std::endl;
}
// Clean up
curl_easy_cleanup(curl);
file.close();
}
// Cleanup libcurl
curl_global_cleanup();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment