Skip to content

Instantly share code, notes, and snippets.

Created September 20, 2023 16:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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 = "";
// Output file name
const char* outputFile = "downloaded.html";
// Initialize libcurl
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;
std::cout << "Download successful." << std::endl;
// Clean up
// Cleanup libcurl
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment