Created
May 7, 2016 05:23
-
-
Save vayn/5b9c35ffe635d54c5b0898169a18e989 to your computer and use it in GitHub Desktop.
Curl_Player
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.c | |
// PointerPlayer | |
// | |
// Created by Vicent Tsai on 16/3/1. | |
// Copyright © 2016年 HeZhi Corp. All rights reserved. | |
// | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <curl/curl.h> | |
#include <curl/easy.h> | |
void safeFree(void** pp) { | |
if (pp != NULL & *pp != NULL) { | |
free(*pp); | |
*pp = NULL; | |
} | |
} | |
#define safeFree(p) safeFree((void**)&(p)) | |
typedef struct _buffer { | |
char *buffer; | |
size_t size; | |
} Buffer; | |
static size_t WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) { | |
size_t realsize = size * nmemb; | |
Buffer *mem = (Buffer*)data; | |
mem->buffer = realloc(mem->buffer, mem->size+realsize+1); | |
if (mem->buffer) { | |
memcpy(&(mem->buffer[mem->size]), ptr, realsize); | |
mem->size += realsize; | |
mem->buffer[mem->size] = 0; | |
} | |
return realsize; | |
} | |
int main(int argc, char const* argv[]) { | |
curl_global_init(CURL_GLOBAL_ALL); | |
CURL *handler; | |
CURLcode result; | |
long http_code; | |
double content_length; | |
Buffer output; | |
FILE *fp; | |
fp = fopen("/tmp/fun.html", "w"); | |
if (!fp) { | |
return 1; | |
} | |
output.buffer = NULL; | |
output.size = 0; | |
handler = curl_easy_init(); | |
curl_easy_setopt(handler, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); | |
curl_easy_setopt(handler, CURLOPT_WRITEDATA, (void *)&output); | |
curl_easy_setopt(handler, CURLOPT_URL, "http://www.v2ex.com"); | |
result = curl_easy_perform(handler); | |
if (result == 0) { | |
fprintf(fp, "%s\n", output.buffer); | |
fclose(fp); | |
printf("file downloaded\n"); | |
} else { | |
printf("ERROR in dowloading file\n"); | |
fclose(fp); | |
} | |
printf("get http return code\n"); | |
curl_easy_getinfo(handler, CURLINFO_RESPONSE_CODE, &http_code); | |
printf("http code: %lu\n", http_code); | |
printf("get size of download page\n"); | |
curl_easy_getinfo(handler, CURLINFO_SIZE_DOWNLOAD, &content_length); | |
printf("length: %g\n", content_length); | |
printf("buffer size: %zu\n", output.size); | |
curl_easy_cleanup(handler); | |
if (output.buffer) { | |
printf("%.*s\n", 100, output.buffer+10); | |
safeFree(output.buffer); | |
output.size = 0; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment