I want to store a result for character string with libcurl

最后都变了- 提交于 2020-01-30 06:26:14

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/897027/i-want-to-store-a-result-for-character-string-with-libcurl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!