0

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.

user629034
  • 659
  • 2
  • 11
  • 30

3 Answers3

1

[Subminiature language-agnostic comment: are you sure it's the best to write raw PNG data to stdout?]

Also, it seems you're using libcurl to get that image. Well, if you don't set a custom callback function for the CURL handle, then it will just write straight to stdout.

However, if this is not what you're intending to do, you may want to have a look at realloc().

1

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 ?

Paolo
  • 15,233
  • 27
  • 70
  • 91
0

You're telling fwrite to write 20000 objects the size of a pointer. That's because sizeof(raw_image) returns the size of raw_image, which is a pointer, and therefore 4 bytes on most 32-bit machines and 8 bytes on most 64-bit machines. It does not return the size of the buffer raw_image points to.

I don't know how you can determine the size of the image you're downloading, but you need to determine that size somehow. And once you do, your fwrite call should look like this:

fwrite(raw_image, 1, sizeOfTheImageInBytes, stdout)
Carey Gregory
  • 6,836
  • 2
  • 26
  • 47