Simple curl download example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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