libcurl
De Wicri Outils
libcurl
est une bibliothèque logicielle écrite en langage C qui permet de manipuler des ressources repérées par leurs URL.
La commande cURL
est écrite à l'aide de cette bibliothèque.
Sommaire
Exemples d'emploi
Exemple de base
Le programme ci dessous[1] accède au document (html) localisé à l'url http://ticri.inpl-nancy.fr, le range dans la chaîne contenue dans la structure s et l'imprime.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
struct string {
char *ptr;
size_t len;
};
void init_string(struct string *s) {
s->len = 0;
s->ptr = malloc(s->len+1);
if (s->ptr == NULL) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
s->ptr[0] = '\0';
}
size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s)
{
size_t new_len = s->len + size*nmemb;
s->ptr = realloc(s->ptr, new_len+1);
if (s->ptr == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(s->ptr+s->len, ptr, size*nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return size*nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
struct string s;
init_string(&s);
curl_easy_setopt(curl, CURLOPT_URL, "http://ticri.inpl-nancy.fr");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
res = curl_easy_perform(curl);
printf("%s\n", s.ptr);
free(s.ptr);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
Si testCurl.c
est le nom du fichier correspondant au code source précédent, la compilation se fait généralement par une commande du type :
gcc testCurl.c -lcurl -ll -o testCurl
./testCurl
Autre version
Le module Buffer de la bibliothèque Dilib permet une écriture plus simple :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "Buffer.h"
Buffer *buf1;
size_t writefunc(void *ptr, size_t size, size_t nmemb, Buffer *buf)
{
BufferStrncat(buf, ptr, size*nmemb);
return size*nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
buf1=BufferCreate(10000,10000);
BufferStrcpy(buf1,"");
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://ticri.inpl-nancy.fr");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, buf1);
res = curl_easy_perform(curl);
printf("%s\n", BufferString(buf1));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
Voir aussi
Liens externes
Notes
- ↑ Exemple extrait du site http://stackoverflow.com et testé sur MacBook Pro sous Mac OS X
http://stackoverflow.com/questions/2329571/c-libcurl-get-output-into-a-string