分类: C/C++
2007-03-28 15:34:17
#include;
#include;
#include;
int main(int argc, char *argv[])
{
CURL *curl; //定义CURL类型的指针
CURLcode res; //定义CURLcode类型的变量
if(argc!=2)
{
printf("Usage : file;\n");
exit(1);
}
curl = curl_easy_init(); //初始化一个CURL类型的指针
if(curl!=NULL)
{
//设置curl选项. 其中CURLOPT_URL是让用户指定url. argv[1]中存放的命令行传进来的网址
curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
//调用curl_easy_perform 执行我们的设置.并进行相关的操作. 在这里只在屏幕上显示出来.
res = curl_easy_perform(curl);
//清除curl操作.
curl_easy_cleanup(curl);
}
return 0;
}
#include;
#include;
#include;
#include;
#include;
#include;
FILE *fp; //定义FILE类型指针
size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) //这个函数是为了符合CURLOPT_WRITEFUNCTION, 而构造的
{
int written = fwrite(ptr, size, nmemb, (FILE *)fp);
return written;
}
int main(int argc, char *argv[])
{
CURL *curl;
curl_global_init(CURL_GLOBAL_ALL);
curl=curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
if((fp=fopen(argv[1],"w"))==NULL)
{
curl_easy_cleanup(curl);
exit(1);
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); //CURLOPT_WRITEFUNCTION 将后继的动作交给write_data函数处理
curl_easy_perform(curl);
curl_easy_cleanup(curl);
exit(0);
}
#include;
#include;
#include;
#include;
struct FtpFile //定义一个结构为了传递给my_fwrite函数.可用curl_easy_setopt的CURLOPT_WRITEDATA选项传递
{
char *filename;
FILE *stream;
};
int my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
struct FtpFile *out=(struct FtpFile *)stream; // stream指针其实就是 指向struct FtpFile ftpfile的
if(out && !out->;stream)
{
out->;stream=fopen(out->;filename, "wb"); //没有这个流的话就创建一个 名字是out->;filename.
if(!out->;stream)
return -1;
}
return fwrite(buffer, size, nmemb, out->;stream);
}
int main(int argc, char *argv[])
{
CURL *curl;
CURLcode res;
struct FtpFile ftpfile={argv[2],NULL}; //初始化一个FtpFile结构
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL,argv[1]);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile); //给相关函数的第四个参数 传递一个结构体的指针
curl_easy_setopt(curl, CURLOPT_VERBOSE, TRUE); //CURLOPT_VERBOSE 这个选项很常用 用来在屏幕上显示对服务器相关操作返回的信息
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(CURLE_OK != res)
fprintf(stderr, "curl told us %d\n", res);
}
if(ftpfile.stream)
fclose(ftpfile.stream);
curl_global_cleanup();
return 0;
}