How to retrieve file from HTTP server using libcurl (or another way)?

1.5k views Asked by At

I am trying to fetch stock quotes from yahoo finance in C. I know how to get the file i want, it's simple enough you input this URL in your browser for example : download.finance.yahoo.com/d/quotes.csv?s=YHOO+GOOG+MSFT&f=sl1d1t1c1hgvbap2 and it automatically download the file. My problem is that i wanted to fetch this file using a C program, I've found libcurl that apparently enable you to do that but my effort linked to nothing. I would like to know how to fetch such a file using libcurl or if it is not possible with libcurl how to fetch a file from a URL.

This is my libcurl code to fetch the file that didn't work (no error just an empty file at the end) :

#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <string.h>

size_t write_data(void* ptr,size_t size,size_t nmemb,FILE* stream){
    size_t written;
    written=fwrite(ptr,size,nmemb,stream);
}

int main(void){
    CURL* curl;
    FILE* fp;
    CURLcode res;
    char* url="http://download.finance.yahoo/d/quotes.csv?s=YHOO+GOOG+MSFT&f=sl1d1t1c1hgvbap2";
    //char* url="https://marketviewer.equiduct.com";
    char outfilename[FILENAME_MAX]="test.txt";
    curl=curl_easy_init();
    if(curl){
        fp=fopen(outfilename,"wb");
        curl_easy_setopt(curl,CURLOPT_URL, url);
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_data);
        curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
        res=curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    else {
        printf("Error !!!\n");
    }
    return 0;
}
1

There are 1 answers

6
antonpuz On

try using their example for getting a file:

http://curl.haxx.se/libcurl/c/getinmemory.html

description: describes how you can use the callback system to fetch documents into a ram buffer with no file writing necessary.

you should save the data to a file if needed.