Source Code File 04-01_save2file.c

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>

int main()
{
    CURL *curl;
    CURLcode r;
    char address[] =
        "https://c-for-dummies.com/curl_test.txt";
    char filename[] = "output.txt";
    FILE *fh;

    /* open fh file */
    fh = fopen(filename,"w");
    if( fh==NULL )
    {
        fprintf(stderr,"Can't create '%s'",
                filename
               );
        exit(1);
    }

    /* initialuze curl */
    curl = curl_easy_init();

    /* set options */
    curl_easy_setopt(curl,
            CURLOPT_URL,address);
    curl_easy_setopt(curl,
            CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl,
            CURLOPT_WRITEFUNCTION, NULL);
    curl_easy_setopt(curl,
            CURLOPT_WRITEDATA, fh);
    
    /* read the address */
    r = curl_easy_perform(curl);
    if( r != CURLE_OK )
    {
        fprintf(stderr,"curl failed: %s\n",
                curl_easy_strerror(r)
                );
        fclose(fh);
        exit(1);
    }
    
    /* cleanup and close */
    curl_easy_cleanup(curl);
    fclose(fh);
    /* let the user know what's going on */
    printf("File '%s' written\n",filename);

    return(0);
}

Notes

* Wide version of this code (statements not split)