Created
November 28, 2014 15:10
-
-
Save alepez/833adf00c826716948c2 to your computer and use it in GitHub Desktop.
curl download c++11
This file contains hidden or 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 <cstdio> | |
#include <curl/curl.h> | |
#include <curl/easy.h> | |
#include <string> | |
#include <cassert> | |
#include <stdexcept> | |
#include <sstream> | |
#include <iostream> | |
void download(const std::string& url, const std::string& filename) { | |
auto curl = curl_easy_init(); | |
assert(curl); | |
auto fp = fopen(filename.c_str(), "wb"); | |
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite); | |
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip"); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); | |
if (CURLE_OK != curl_easy_perform(curl)) { | |
throw std::runtime_error("Cannot perform download " + url + " -> " + filename); | |
} | |
curl_easy_cleanup(curl); | |
fclose(fp); | |
} | |
std::string getStringFromUrl(const std::string& url) { | |
std::stringstream ss; | |
auto curl = curl_easy_init(); | |
assert(curl); | |
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ss); | |
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "gzip"); | |
auto fn = static_cast<size_t (*)(void*, size_t, size_t, void*)>([](void* ptr, size_t size, size_t nmemb, void* stream) { | |
std::stringstream& ss = *reinterpret_cast<std::stringstream*>(stream); | |
ss.write(reinterpret_cast<char*>(ptr), size * nmemb); | |
return size * nmemb; | |
}); | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fn); | |
if (CURLE_OK != curl_easy_perform(curl)) { | |
throw std::runtime_error("Cannot perform download " + url); | |
} | |
curl_easy_cleanup(curl); | |
return ss.str(); | |
} | |
int main(int argc, char* argv[]) { | |
if (argc == 2) { | |
std::cout << getStringFromUrl(argv[1]); | |
} else if (argc == 3) { | |
download(argv[1], argv[2]); | |
} else { | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment