0

I'm trying to get some data from a certain web-based api using the libcurl c api. Curl calls the api fine. However, size_t nmemb is too small to hold the response. Somehow it is "cut off" at 1280. Does anyone know how to solve this? Also size_t size is 1..

These are the functions I use:

int http_call(char *url) {

    CURL *curl;
    FILE *curlfile;
    CURLcode res;

    char outfilename[FILENAME_MAX] = "/usr/local/var/log/ndcurl";
    curl = curl_easy_init();
    if (curl) {

        curlfile = fopen(outfilename,"w");
        curl_easy_setopt(curl, CURLOPT_URL, url);

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_release_data);

        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        res = curl_easy_perform(curl);

        curl_easy_cleanup(curl);
        fclose(curlfile);

    }

    return 0;

}

And the callback:

static size_t write_release_data(void *buffer, size_t size, size_t nmemb, void *userp) {

    char **response_ptr =  (char**)userp;
    *response_ptr = strndup(buffer, (size_t)(size *nmemb));
    printf("The Response: %s", *response_ptr);

    return 0;

}

1 Answer 1

1

You need to fix your callback to return the actual number of bytes written. From the documentation

Pass a pointer to a function that matches the following prototype: size_t function( char *ptr, size_t size, size_t nmemb, void *userdata); This function gets called by libcurl as soon as there is data received that needs to be saved. The size of the data pointed to by ptr is size multiplied with nmemb, it will not be zero terminated. Return the number of bytes actually taken care of. If that amount differs from the amount passed to your function, it'll signal an error to the library. This will abort the transfer and return CURLE_WRITE_ERROR.

If you return size * nmemb, libcurl should call your function again with the rest of the response.

3
  • it can also be noted that the callback will then be called multiple times until all data has been delivered Jun 15, 2012 at 8:08
  • Ok great, it works now. One more question: I need to pass the complete response to another function. How would I do that?
    – Thomas K
    Jun 15, 2012 at 8:13
  • You'll need to cache the response somewhere (global created with malloc, file on disk, etc.) and wait for curl to finish sending it to you. You'll have to read the curl docs to find out how it signals that the transfer is complete. Make use of the userdata parameter to your callback function to keep track of the state, in case you are transferring multiple URLs.
    – tomlogic
    Jun 15, 2012 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.