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

  1. #include <string>
  2. #include <iostream>
  3. #include "curl/curl.h"
  4. using namespace std;
  5. // Write any errors in here
  6. static char errorBuffer[CURL_ERROR_SIZE];
  7. // Write all expected data in here
  8. static string buffer;
  9. // This is the writer call back function used by curl
  10. static int writer(char *data, size_t size, size_t nmemb,
  11. std::string *buffer)
  12. {
  13. // What we will return
  14. int result = 0;
  15. // Is there anything in the buffer?
  16. if (buffer != NULL)
  17. {
  18. // Append the data to the buffer
  19. buffer->append(data, size * nmemb);
  20. // How much did we write?
  21. result = size * nmemb;
  22. }
  23. return result;
  24. }
  25. // You know what this does..
  26. void usage()
  27. {
  28. cout < < "curltest: \n" << endl;
  29. cout << " Usage: curltest url\n" << endl;
  30. }
  31. /*
  32. * The old favorite
  33. */
  34. int main(int argc, char* argv[])
  35. {
  36. if (argc > 1)
  37. {
  38. string url(argv[1]);
  39. cout < < "Retrieving " << url << endl;
  40. // Our curl objects
  41. CURL *curl;
  42. CURLcode result;
  43. // Create our curl handle
  44. curl = curl_easy_init();
  45. if (curl)
  46. {
  47. // Now set up all of the curl options
  48. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
  49. curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
  50. curl_easy_setopt(curl, CURLOPT_HEADER, 0);
  51. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  52. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
  53. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
  54. // Attempt to retrieve the remote page
  55. result = curl_easy_perform(curl);
  56. // Always cleanup
  57. curl_easy_cleanup(curl);
  58. // Did we succeed?
  59. if (result == CURLE_OK)
  60. {
  61. cout << buffer << "\n";
  62. exit(0);
  63. }
  64. else
  65. {
  66. cout << "Error: [" << result << "] - " << errorBuffer;
  67. exit(-1);
  68. }
  69. }
  70. }
  71. }

Den Code habe ich von luckyspin.org