C++: libcurl
Ab Oktober werde ich wohl verstärkt mit C++ arbeiten und da bietet es sich ja schon ab vorher ein paar interessante Links und Codeschnipsel zu sammeln. Den Anfang macht cURL bzw libcurl.
cURL ist ein Programm, um einzelne Dateien aus dem Internet ohne Browser zu transferieren.
Der Name ist eine Abkürzung von Client for URLs. Zu den unterstützten Protokollen gehören u. a. HTTP, HTTPS, FTP, FTPS, DICT, LDAP, RTMP, Gopher. Das Programm steht unter der MIT-Lizenz und ist auf viele verschiedene Betriebssysteme portiert worden.Wikipedia
#include <string>#include <iostream>#include "curl/curl.h"using namespace std;// Write any errors in herestatic char errorBuffer[CURL_ERROR_SIZE];// Write all expected data in herestatic string buffer;// This is the writer call back function used by curlstatic int writer(char *data, size_t size, size_t nmemb,std::string *buffer){// What we will returnint result = 0;// Is there anything in the buffer?if (buffer != NULL){// Append the data to the bufferbuffer->append(data, size * nmemb);// How much did we write?result = size * nmemb;}return result;}// You know what this does..void usage(){cout < < "curltest: \n" << endl;cout << " Usage: curltest url\n" << endl;}/** The old favorite*/int main(int argc, char* argv[]){if (argc > 1){string url(argv[1]);cout < < "Retrieving " << url << endl;// Our curl objectsCURL *curl;CURLcode result;// Create our curl handlecurl = curl_easy_init();if (curl){// Now set up all of the curl optionscurl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);curl_easy_setopt(curl, CURLOPT_URL, argv[1]);curl_easy_setopt(curl, CURLOPT_HEADER, 0);curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);// Attempt to retrieve the remote pageresult = curl_easy_perform(curl);// Always cleanupcurl_easy_cleanup(curl);// Did we succeed?if (result == CURLE_OK){cout << buffer << "\n";exit(0);}else{cout << "Error: [" << result << "] - " << errorBuffer;exit(-1);}}}}
Den Code habe ich von luckyspin.org