Search code examples
ccurlfwrite

fwrite dynamic size


I am trying to print a dynamically downloaded image returned by cURL as shown :

    char *raw_image = malloc(1024);

    raw_image = doCurl("GET", img_url, NULL, NULL);

    printf("Content-Type: image/png\n\n");

    fwrite(raw_image, sizeof(raw_image), 20000, stdout);

If I do size smaller than 20000 - image gets cut. How can I make that number dynamic? I don't want to write to a file - stdout is the best option.

Any help is appreciated.


Solution

  • Ideally you need a way to know the size of the file (image) you are downloading.

    Use libcurl to fetch the header first and get the size.

    Let say you store size in s

    When you alloc the buffer you shoud do

    char *raw_image = malloc(s);
    

    Because s is the size of the data you have to hold not 1024 bytes!

    Download the file and store it in raw_image

    Then

    fwrite(raw_image, 1, s, stdout);
    

    Note that sizeof(raw_image) is the size of the pointer to your buffer, so 8 bytes in a 64bit hw architecture. It's not the size of the file!

    -

    But....

    -

    You're fetching an image, and streming it on stdout.

    Why don't you do a simple call to curl ?