《用 libcurl 实现 HTTP 下载文件,其中设置了超时时间,以便在网络异常时能够快速中止下载。》

  CURLOPT_TIMEOUT选项设置了超时时间为 10 秒,如果在这个时间内没有下载完成,则会返回一个超时错误,可以在回调函数中进行错误处理。如果网络异常或其他错误,也会在curl_easy_perform函数中立即返回错误,而不是一直阻塞等待。

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

int download_file(const char *url, const char *file_path) {
    CURL *curl_handle = NULL;
    CURLcode res;

    FILE *fp = NULL;
    int ret = -1;

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl_handle = curl_easy_init();

    if (curl_handle) {
        fp = fopen(file_path, "wb");
        if (fp == NULL) {
            printf("open file error\n");
            goto cleanup;
        }

        curl_easy_setopt(curl_handle, CURLOPT_URL, url);
        curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, fp);

        // 设置超时时间
        curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 10L);

        res = curl_easy_perform(curl_handle);

        if (res != CURLE_OK) {
            printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            goto cleanup;
        }

        ret = 0;

    }

cleanup:
    if (fp != NULL) {
        fclose(fp);
    }

    if (curl_handle) {
        curl_easy_cleanup(curl_handle);
    }

    curl_global_cleanup();

    return ret;
}

int main() {
    download_file("http://example.com/test.txt", "test.txt");
    return 0;
}

 

posted @ 2023-02-16 14:56  一个不知道干嘛的小萌新  阅读(288)  评论(0编辑  收藏  举报