开发者

Cant write file I downloaded using curl in C

I have some C code using curl that I want to use to download a csv file. When I use it though, instead of getting and writing the file to disk, it writes the HTML of the webpage or doesnt write anyth开发者_如何学编程ing at all. Here is my code:

size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    return fwrite(ptr, size, nmemb, stream);
}

void *downloadFile(void *ptr)
{
    CURL *curl;
    CURLcode res;
    FILE *outfile;
    char *symbol = (char *)ptr;

    curl = curl_easy_init();
    if(curl)
    {
        outfile = fopen(symbol, "w");
        char url[100] = "http://finance.yahoo.com/d/quotes.csv?s=";
        strcat(url, symbol);
        strcat(url, "&f=npl1");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(outfile);
    }
}


As wrote on the official doc :

The internal default function will write the data to the FILE * given with CURLOPT_WRITEDATA.

So, for your app, you don't need to make your callback function.

void *downloadFile(void *ptr)
{
    CURL *curl;
    CURLcode res;
    FILE *outfile;
    char *symbol = (char *)ptr;

    curl = curl_easy_init();
    if(curl)
    {
        outfile = fopen(symbol, "w");
        char url[100] = "http://finance.yahoo.com/d/quotes.csv?s=";
        strcat(url, symbol);
        strcat(url, "&f=npl1");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(outfile);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜