tags:

views:

402

answers:

3

I write a program with libcurl.

#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

#define URL_MAX 256

int main(int argc, char *args[])
{
    CURL *curl;
    CURLcode res;
        curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, args[1]);
    curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    return 0;
}

$ gcc tinyCurl.c $ gcc curl-config --libs tinyCurl.c $ ./a.out http://example.com/ I examine search it google but I can't find . I want to store char[] not stdout.

Is a question of the beginner thanking you in advance

+1  A: 

Check out the curl_easy_setopt() function.

You would want to register a callback using CURLOPT_WRITEFUNCTION - this callback would be called whenever data is received. From within the callback you could do whatever you want with the data.

Note - this is somewhat tricky stuff for a beginner. You need to understand what function pointers are.

(this answer is based on reading the API in http://curl.haxx.se/libcurl/c/curl_easy_setopt.html - I have never used libcurl).

EDIT -
Here is an example found by googling for CURLOPT_WRITEFUNCTION, in the curl-library mailing list. This example is by Daniel Stenberg.

Hexagon
Thanks alot but , Could you give me more detail code examples?
ffffff
+1  A: 

I get it !

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>

size_t  write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
  char buf[size*nmemb+1];
  char * pbuf = &buf[0];
  memset(buf, '\0', size*nmemb+1);
  size_t i = 0;
  for(;  i < nmemb ; i++){
    strncpy(pbuf,ptr,size);
    pbuf += size;
    ptr += size;
  }
  printf("%s",buf);
  return size * nmemb;
}

int main(int argc, char **argv)
{
    CURL *curl_handle;
    curl_handle = curl_easy_init();
    enum{Command,URL,NumCommands};
    if(NumCommands != argc){
        fprintf(stderr,"Usage : %s <url>\n",argv[0]);
        return 1;
    }
    curl_easy_setopt(curl_handle,   CURLOPT_URL, argv[URL]);
    curl_easy_setopt(curl_handle,   CURLOPT_NOPROGRESS  ,1);
    curl_easy_setopt(curl_handle,   CURLOPT_WRITEFUNCTION,&write_data);
    curl_easy_perform(curl_handle);
    curl_easy_cleanup(curl_handle);
    return 0;
}

Thank you Hexagon.

ffffff
Then, accept Hexagon's answer
bortzmeyer
sure.I'll do it
ffffff
A: 

This was helpful. Thanks!