使用libcurl 函数库获取网页数据代码

jopen 11年前

使用libcurl 获取网页数据代码

/**  * File: w3G.c  * libcurl is an open source lib for url.  *  * Copyright: (c) T-ware Inc.  *  * Function: get 3G data from internet  *  * Author: Tody Guo  * Date: 2013-10-06  *  **/    //#include "stdafx.h"  #include <stdio.h>  #include <curl/curl.h>    //#pragma comment(lib, "libcurl.lib")    void oops(char *msg)  {  fprintf(stderr, "%s\nReturn code: 1", msg);  exit(1);  }    size_t write_data(void *buffer, size_t size, size_t nmemb, void *user_p)  {  FILE *f = (FILE *) user_p;    size_t return_size = fwrite(buffer, size, nmemb, f);    return return_size;  }    int main(int argc, char* argv[])  {  CURL *curl;  CURLcode resCode;  FILE *fp =NULL;  char url[256]="www.baidu.com";    printf("Version: %s\n", curl_version());    if (argc>=2)  {  strncpy(url, argv[1], 256);  }    curl = curl_easy_init();  if (NULL==curl)  oops("init failed!");    curl_easy_setopt(curl, CURLOPT_URL, url);    if (argc == 3)  {  fp = fopen(argv[2], "wb+");  if (fp==NULL)  oops("open file failed");  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);  curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);  fprintf(stderr, "Saving to file(%s)...", argv[2]);  }    resCode = curl_easy_perform(curl);    if (resCode!=0)  oops((char *)curl_easy_strerror(resCode));    curl_easy_cleanup(curl);    if(fp != NULL)  fclose(fp);    fprintf(stderr, "\nReturn code: 0");  return 0;  }