无法写入我在C中使用curl下载的文件

时间:2010-11-15 19:13:57

标签: curl

我有一些使用curl的C代码,我想用来下载csv文件。当我使用它时,它不是将文件写入磁盘,而是写入网页的HTML或根本不写任何内容。这是我的代码:

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);
    }
}

1 个答案:

答案 0 :(得分:0)

正如官方文件中所写:

  

内部默认函数会将数据写入CURLOPT_WRITEDATA给出的FILE *。

因此,对于您的应用,您不需要进行回调功能。

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);
    }
}