summaryrefslogtreecommitdiffstats
path: root/curl_tofile.c
blob: 7cd25ca9e8658a948905592f0b963a5eb2e45ec6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <curl/curl.h>

size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    /* return size * nmemb; */
    return fwrite(ptr, size, nmemb, (FILE *) userdata);
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "usage: %s <url>\n", argv[0]);
        return 1;
    }

    CURL *curl_handle;
    CURLcode ret;

    curl_handle = curl_easy_init();
    if (curl_handle)
    {
        curl_easy_setopt(curl_handle, CURLOPT_URL, argv[1]);
        curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1L);
        /* some servers don't like requests that are made without a user-agent
         * field, so we provide one */ 
        curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
        char err_buff[CURL_ERROR_SIZE];
        curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, err_buff);
        /* send all data to this function  */
        curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);

        /* by default passes NULL aka stdout */
        FILE *fl;
        if ((fl = fopen("dump.curl", "w")))
            curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, fl);
        else
            curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, stdout);

        if ((ret = curl_easy_perform(curl_handle)) != CURLE_OK)
            fprintf(stderr, "%s\n", err_buff);
        else
        {
            /* ask for the content-type */
            char *ct;
            ret = curl_easy_getinfo(curl_handle, CURLINFO_CONTENT_TYPE, &ct);
            if ((CURLE_OK == ret) && ct)
                printf("Content-Type: %s\n", ct);
        }

        /* always cleanup */
        fclose(fl);
        curl_easy_cleanup(curl_handle);
    }

    return 0;
}