2

I am using libcurl to download binary files, but i want to read the header of these binary files, which are the first couple of bytes. If the headers byte match a condition I want to continue the download, else I don't want to cancel the download.

size_t writeData(void *contents, size_t size, 
                                  size_t nmemb, FILE *stream) {

    const unsigned char * cPtr;
    cPtr = (const unsigned char*)contents;
    bool isByte = checkByte(cPtr, nmemb);
    if (isByte){
        // Continue Download, and write to disk.
        size_t written = fwrite(contents, size, nmemb, stream);
        return written;
        }
    else
        // Kill Download.
}
leakybytes
  • 359
  • 4
  • 12
  • Given that this is described very detailed in the docs, as quoted in the answer by @Anton, it does beg the question where you tried to find the information before you asked this question... – Daniel Stenberg Aug 22 '16 at 07:24

1 Answers1

1

Define your own write function setting the option CURLOPT_WRITEFUNCTION. Look at the docs here: https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html.

To abort transfer you simply need to return from write function the value, lesser than count of bytes passed to your write function. Corresponding lines from the docs:

If that amount differs from the amount passed to your callback function, it'll signal an error condition to the library. This will cause the transfer to get aborted and the libcurl function used will return CURLE_WRITE_ERROR

Anton Malyshev
  • 8,686
  • 2
  • 27
  • 45
  • is there another way? say for example curl waiting for server to send data "weak connection / slow internet", do i have to wait until curl receive data and my callback function get called? in other words is there a way to immediately terminate curl "safely"? – Mahmoud Elshahat Apr 15 '19 at 02:32
  • ok i figured this out, using progress callback will solve these issues as curl will call it at least once per seconds even if no data received from the server, i added explanation in this answer: https://stackoverflow.com/a/55682675/10146012 – Mahmoud Elshahat Apr 15 '19 at 04:50